1//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "AArch64ExpandImm.h"
14#include "AArch64ISelLowering.h"
15#include "AArch64CallingConvention.h"
16#include "AArch64MachineFunctionInfo.h"
17#include "AArch64PerfectShuffle.h"
18#include "AArch64RegisterInfo.h"
19#include "AArch64Subtarget.h"
20#include "MCTargetDesc/AArch64AddressingModes.h"
21#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Analysis/VectorUtils.h"
33#include "llvm/CodeGen/CallingConvLower.h"
34#include "llvm/CodeGen/MachineBasicBlock.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
38#include "llvm/CodeGen/MachineInstrBuilder.h"
39#include "llvm/CodeGen/MachineMemOperand.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
41#include "llvm/CodeGen/RuntimeLibcalls.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/CodeGen/SelectionDAGNodes.h"
44#include "llvm/CodeGen/TargetCallingConv.h"
45#include "llvm/CodeGen/TargetInstrInfo.h"
46#include "llvm/CodeGen/ValueTypes.h"
47#include "llvm/IR/Attributes.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/DerivedTypes.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/GetElementPtrTypeIterator.h"
54#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
58#include "llvm/IR/IntrinsicInst.h"
59#include "llvm/IR/Intrinsics.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/OperandTraits.h"
62#include "llvm/IR/PatternMatch.h"
63#include "llvm/IR/Type.h"
64#include "llvm/IR/Use.h"
65#include "llvm/IR/Value.h"
66#include "llvm/MC/MCRegisterInfo.h"
67#include "llvm/Support/Casting.h"
68#include "llvm/Support/CodeGen.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/Compiler.h"
71#include "llvm/Support/Debug.h"
72#include "llvm/Support/ErrorHandling.h"
73#include "llvm/Support/KnownBits.h"
74#include "llvm/Support/MachineValueType.h"
75#include "llvm/Support/MathExtras.h"
76#include "llvm/Support/raw_ostream.h"
77#include "llvm/Target/TargetMachine.h"
78#include "llvm/Target/TargetOptions.h"
79#include <algorithm>
80#include <bitset>
81#include <cassert>
82#include <cctype>
83#include <cstdint>
84#include <cstdlib>
85#include <iterator>
86#include <limits>
87#include <tuple>
88#include <utility>
89#include <vector>
90
91using namespace llvm;
92using namespace llvm::PatternMatch;
93
94#define DEBUG_TYPE "aarch64-lower"
95
96STATISTIC(NumTailCalls, "Number of tail calls");
97STATISTIC(NumShiftInserts, "Number of vector shift inserts");
98STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
99
100static cl::opt<bool>
101EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
102 cl::desc("Allow AArch64 SLI/SRI formation"),
103 cl::init(false));
104
105// FIXME: The necessary dtprel relocations don't seem to be supported
106// well in the GNU bfd and gold linkers at the moment. Therefore, by
107// default, for now, fall back to GeneralDynamic code generation.
108cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 cl::init(false));
112
113static cl::opt<bool>
114EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115 cl::desc("Enable AArch64 logical imm instruction "
116 "optimization"),
117 cl::init(true));
118
119/// Value type used for condition codes.
120static const MVT MVT_CC = MVT::i32;
121
122AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
123 const AArch64Subtarget &STI)
124 : TargetLowering(TM), Subtarget(&STI) {
125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
131
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
134 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
135
136 if (Subtarget->hasFPARMv8()) {
137 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
138 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
139 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
140 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
141 }
142
143 if (Subtarget->hasNEON()) {
144 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
145 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32);
148 addDRTypeForNEON(MVT::v8i8);
149 addDRTypeForNEON(MVT::v4i16);
150 addDRTypeForNEON(MVT::v2i32);
151 addDRTypeForNEON(MVT::v1i64);
152 addDRTypeForNEON(MVT::v1f64);
153 addDRTypeForNEON(MVT::v4f16);
154
155 addQRTypeForNEON(MVT::v4f32);
156 addQRTypeForNEON(MVT::v2f64);
157 addQRTypeForNEON(MVT::v16i8);
158 addQRTypeForNEON(MVT::v8i16);
159 addQRTypeForNEON(MVT::v4i32);
160 addQRTypeForNEON(MVT::v2i64);
161 addQRTypeForNEON(MVT::v8f16);
162 }
163
164 // Compute derived properties from the register classes
165 computeRegisterProperties(Subtarget->getRegisterInfo());
166
167 // Provide all sorts of operation actions
168 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
169 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
170 setOperationAction(ISD::SETCC, MVT::i32, Custom);
171 setOperationAction(ISD::SETCC, MVT::i64, Custom);
172 setOperationAction(ISD::SETCC, MVT::f16, Custom);
173 setOperationAction(ISD::SETCC, MVT::f32, Custom);
174 setOperationAction(ISD::SETCC, MVT::f64, Custom);
175 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
176 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
177 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
178 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
180 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
181 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
182 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
183 setOperationAction(ISD::SELECT, MVT::i32, Custom);
184 setOperationAction(ISD::SELECT, MVT::i64, Custom);
185 setOperationAction(ISD::SELECT, MVT::f16, Custom);
186 setOperationAction(ISD::SELECT, MVT::f32, Custom);
187 setOperationAction(ISD::SELECT, MVT::f64, Custom);
188 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
190 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
191 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
192 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
193 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
194 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
195
196 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
197 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
198 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
199
200 setOperationAction(ISD::FREM, MVT::f32, Expand);
201 setOperationAction(ISD::FREM, MVT::f64, Expand);
202 setOperationAction(ISD::FREM, MVT::f80, Expand);
203
204 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
205
206 // Custom lowering hooks are needed for XOR
207 // to fold it into CSINC/CSINV.
208 setOperationAction(ISD::XOR, MVT::i32, Custom);
209 setOperationAction(ISD::XOR, MVT::i64, Custom);
210
211 // Virtually no operation on f128 is legal, but LLVM can't expand them when
212 // there's a valid register class, so we need custom operations in most cases.
213 setOperationAction(ISD::FABS, MVT::f128, Expand);
214 setOperationAction(ISD::FADD, MVT::f128, Custom);
215 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
216 setOperationAction(ISD::FCOS, MVT::f128, Expand);
217 setOperationAction(ISD::FDIV, MVT::f128, Custom);
218 setOperationAction(ISD::FMA, MVT::f128, Expand);
219 setOperationAction(ISD::FMUL, MVT::f128, Custom);
220 setOperationAction(ISD::FNEG, MVT::f128, Expand);
221 setOperationAction(ISD::FPOW, MVT::f128, Expand);
222 setOperationAction(ISD::FREM, MVT::f128, Expand);
223 setOperationAction(ISD::FRINT, MVT::f128, Expand);
224 setOperationAction(ISD::FSIN, MVT::f128, Expand);
225 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
226 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
227 setOperationAction(ISD::FSUB, MVT::f128, Custom);
228 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
229 setOperationAction(ISD::SETCC, MVT::f128, Custom);
230 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
231 setOperationAction(ISD::SELECT, MVT::f128, Custom);
232 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
233 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
234
235 // Lowering for many of the conversions is actually specified by the non-f128
236 // type. The LowerXXX function will be trivial when f128 isn't involved.
237 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
238 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
239 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
240 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
241 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
242 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
243 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
244 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
245 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
246 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
247 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
248 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
249 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
250 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
251
252 // Variable arguments.
253 setOperationAction(ISD::VASTART, MVT::Other, Custom);
254 setOperationAction(ISD::VAARG, MVT::Other, Custom);
255 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
256 setOperationAction(ISD::VAEND, MVT::Other, Expand);
257
258 // Variable-sized objects.
259 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
260 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
261
262 if (Subtarget->isTargetWindows())
263 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
264 else
265 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
266
267 // Constant pool entries
268 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
269
270 // BlockAddress
271 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
272
273 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
274 setOperationAction(ISD::ADDC, MVT::i32, Custom);
275 setOperationAction(ISD::ADDE, MVT::i32, Custom);
276 setOperationAction(ISD::SUBC, MVT::i32, Custom);
277 setOperationAction(ISD::SUBE, MVT::i32, Custom);
278 setOperationAction(ISD::ADDC, MVT::i64, Custom);
279 setOperationAction(ISD::ADDE, MVT::i64, Custom);
280 setOperationAction(ISD::SUBC, MVT::i64, Custom);
281 setOperationAction(ISD::SUBE, MVT::i64, Custom);
282
283 // AArch64 lacks both left-rotate and popcount instructions.
284 setOperationAction(ISD::ROTL, MVT::i32, Expand);
285 setOperationAction(ISD::ROTL, MVT::i64, Expand);
286 for (MVT VT : MVT::vector_valuetypes()) {
287 setOperationAction(ISD::ROTL, VT, Expand);
288 setOperationAction(ISD::ROTR, VT, Expand);
289 }
290
291 // AArch64 doesn't have {U|S}MUL_LOHI.
292 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
293 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
294
295 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
296 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
297
298 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
299 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
300 for (MVT VT : MVT::vector_valuetypes()) {
301 setOperationAction(ISD::SDIVREM, VT, Expand);
302 setOperationAction(ISD::UDIVREM, VT, Expand);
303 }
304 setOperationAction(ISD::SREM, MVT::i32, Expand);
305 setOperationAction(ISD::SREM, MVT::i64, Expand);
306 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
307 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
308 setOperationAction(ISD::UREM, MVT::i32, Expand);
309 setOperationAction(ISD::UREM, MVT::i64, Expand);
310
311 // Custom lower Add/Sub/Mul with overflow.
312 setOperationAction(ISD::SADDO, MVT::i32, Custom);
313 setOperationAction(ISD::SADDO, MVT::i64, Custom);
314 setOperationAction(ISD::UADDO, MVT::i32, Custom);
315 setOperationAction(ISD::UADDO, MVT::i64, Custom);
316 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
317 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
318 setOperationAction(ISD::USUBO, MVT::i32, Custom);
319 setOperationAction(ISD::USUBO, MVT::i64, Custom);
320 setOperationAction(ISD::SMULO, MVT::i32, Custom);
321 setOperationAction(ISD::SMULO, MVT::i64, Custom);
322 setOperationAction(ISD::UMULO, MVT::i32, Custom);
323 setOperationAction(ISD::UMULO, MVT::i64, Custom);
324
325 setOperationAction(ISD::FSIN, MVT::f32, Expand);
326 setOperationAction(ISD::FSIN, MVT::f64, Expand);
327 setOperationAction(ISD::FCOS, MVT::f32, Expand);
328 setOperationAction(ISD::FCOS, MVT::f64, Expand);
329 setOperationAction(ISD::FPOW, MVT::f32, Expand);
330 setOperationAction(ISD::FPOW, MVT::f64, Expand);
331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
333 if (Subtarget->hasFullFP16())
334 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
335 else
336 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
337
338 setOperationAction(ISD::FREM, MVT::f16, Promote);
339 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
340 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
341 setOperationAction(ISD::FPOW, MVT::f16, Promote);
342 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
343 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
344 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
345 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
346 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
347 setOperationAction(ISD::FCOS, MVT::f16, Promote);
348 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
349 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
350 setOperationAction(ISD::FSIN, MVT::f16, Promote);
351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
352 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
353 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
354 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
355 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
356 setOperationAction(ISD::FEXP, MVT::f16, Promote);
357 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
358 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
359 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
362 setOperationAction(ISD::FLOG, MVT::f16, Promote);
363 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
364 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
365 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
366 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
367 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
368 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
369 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
370 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
371
372 if (!Subtarget->hasFullFP16()) {
373 setOperationAction(ISD::SELECT, MVT::f16, Promote);
374 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
375 setOperationAction(ISD::SETCC, MVT::f16, Promote);
376 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
377 setOperationAction(ISD::FADD, MVT::f16, Promote);
378 setOperationAction(ISD::FSUB, MVT::f16, Promote);
379 setOperationAction(ISD::FMUL, MVT::f16, Promote);
380 setOperationAction(ISD::FDIV, MVT::f16, Promote);
381 setOperationAction(ISD::FMA, MVT::f16, Promote);
382 setOperationAction(ISD::FNEG, MVT::f16, Promote);
383 setOperationAction(ISD::FABS, MVT::f16, Promote);
384 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
385 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
386 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
387 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
388 setOperationAction(ISD::FRINT, MVT::f16, Promote);
389 setOperationAction(ISD::FROUND, MVT::f16, Promote);
390 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
391 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
392 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
393 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
394 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
395
396 // promote v4f16 to v4f32 when that is known to be safe.
397 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
398 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
399 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
400 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
401 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
402 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
403 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
404 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
405 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
406 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
407 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
408 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
409
410 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
411 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
412 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
413 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
414 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
415 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
416 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
417 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
418 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
419 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
420 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
421 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
422 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
423 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
424 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
425
426 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
427 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
428 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
429 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
430 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
431 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
432 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
433 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
434 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
435 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
436 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
437 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
438 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
439 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
440 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
441 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
442 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
443 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
444 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
445 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
446 }
447
448 // AArch64 has implementations of a lot of rounding-like FP operations.
449 for (MVT Ty : {MVT::f32, MVT::f64}) {
450 setOperationAction(ISD::FFLOOR, Ty, Legal);
451 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
452 setOperationAction(ISD::FCEIL, Ty, Legal);
453 setOperationAction(ISD::FRINT, Ty, Legal);
454 setOperationAction(ISD::FTRUNC, Ty, Legal);
455 setOperationAction(ISD::FROUND, Ty, Legal);
456 setOperationAction(ISD::FMINNUM, Ty, Legal);
457 setOperationAction(ISD::FMAXNUM, Ty, Legal);
458 setOperationAction(ISD::FMINIMUM, Ty, Legal);
459 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
460 setOperationAction(ISD::LROUND, Ty, Legal);
461 setOperationAction(ISD::LLROUND, Ty, Legal);
462 setOperationAction(ISD::LRINT, Ty, Legal);
463 setOperationAction(ISD::LLRINT, Ty, Legal);
464 }
465
466 if (Subtarget->hasFullFP16()) {
467 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
468 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
469 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
470 setOperationAction(ISD::FRINT, MVT::f16, Legal);
471 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
472 setOperationAction(ISD::FROUND, MVT::f16, Legal);
473 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
474 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
475 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
476 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
477 }
478
479 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
480
481 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
482
483 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
484 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488
489 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
490 // This requires the Performance Monitors extension.
491 if (Subtarget->hasPerfMon())
492 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
493
494 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
495 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
496 // Issue __sincos_stret if available.
497 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
498 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
499 } else {
500 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
501 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
502 }
503
504 // Make floating-point constants legal for the large code model, so they don't
505 // become loads from the constant pool.
506 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
507 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
508 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
509 }
510
511 // AArch64 does not have floating-point extending loads, i1 sign-extending
512 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
513 for (MVT VT : MVT::fp_valuetypes()) {
514 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
515 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
516 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
517 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
518 }
519 for (MVT VT : MVT::integer_valuetypes())
520 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
521
522 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
523 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
524 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
525 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
526 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
527 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
528 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
529
530 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
531 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
532
533 // Indexed loads and stores are supported.
534 for (unsigned im = (unsigned)ISD::PRE_INC;
535 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
536 setIndexedLoadAction(im, MVT::i8, Legal);
537 setIndexedLoadAction(im, MVT::i16, Legal);
538 setIndexedLoadAction(im, MVT::i32, Legal);
539 setIndexedLoadAction(im, MVT::i64, Legal);
540 setIndexedLoadAction(im, MVT::f64, Legal);
541 setIndexedLoadAction(im, MVT::f32, Legal);
542 setIndexedLoadAction(im, MVT::f16, Legal);
543 setIndexedStoreAction(im, MVT::i8, Legal);
544 setIndexedStoreAction(im, MVT::i16, Legal);
545 setIndexedStoreAction(im, MVT::i32, Legal);
546 setIndexedStoreAction(im, MVT::i64, Legal);
547 setIndexedStoreAction(im, MVT::f64, Legal);
548 setIndexedStoreAction(im, MVT::f32, Legal);
549 setIndexedStoreAction(im, MVT::f16, Legal);
550 }
551
552 // Trap.
553 setOperationAction(ISD::TRAP, MVT::Other, Legal);
554
555 // We combine OR nodes for bitfield operations.
556 setTargetDAGCombine(ISD::OR);
557 // Try to create BICs for vector ANDs.
558 setTargetDAGCombine(ISD::AND);
559
560 // Vector add and sub nodes may conceal a high-half opportunity.
561 // Also, try to fold ADD into CSINC/CSINV..
562 setTargetDAGCombine(ISD::ADD);
563 setTargetDAGCombine(ISD::SUB);
564 setTargetDAGCombine(ISD::SRL);
565 setTargetDAGCombine(ISD::XOR);
566 setTargetDAGCombine(ISD::SINT_TO_FP);
567 setTargetDAGCombine(ISD::UINT_TO_FP);
568
569 setTargetDAGCombine(ISD::FP_TO_SINT);
570 setTargetDAGCombine(ISD::FP_TO_UINT);
571 setTargetDAGCombine(ISD::FDIV);
572
573 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
574
575 setTargetDAGCombine(ISD::ANY_EXTEND);
576 setTargetDAGCombine(ISD::ZERO_EXTEND);
577 setTargetDAGCombine(ISD::SIGN_EXTEND);
578 setTargetDAGCombine(ISD::BITCAST);
579 setTargetDAGCombine(ISD::CONCAT_VECTORS);
580 setTargetDAGCombine(ISD::STORE);
581 if (Subtarget->supportsAddressTopByteIgnored())
582 setTargetDAGCombine(ISD::LOAD);
583
584 setTargetDAGCombine(ISD::MUL);
585
586 setTargetDAGCombine(ISD::SELECT);
587 setTargetDAGCombine(ISD::VSELECT);
588
589 setTargetDAGCombine(ISD::INTRINSIC_VOID);
590 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
591 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
592
593 setTargetDAGCombine(ISD::GlobalAddress);
594
595 // In case of strict alignment, avoid an excessive number of byte wide stores.
596 MaxStoresPerMemsetOptSize = 8;
597 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
598 ? MaxStoresPerMemsetOptSize : 32;
599
600 MaxGluedStoresPerMemcpy = 4;
601 MaxStoresPerMemcpyOptSize = 4;
602 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
603 ? MaxStoresPerMemcpyOptSize : 16;
604
605 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
606
607 setStackPointerRegisterToSaveRestore(AArch64::SP);
608
609 setSchedulingPreference(Sched::Hybrid);
610
611 EnableExtLdPromotion = true;
612
613 // Set required alignment.
614 setMinFunctionAlignment(2);
615 // Set preferred alignments.
616 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
617 setPrefLoopAlignment(STI.getPrefLoopAlignment());
618
619 // Only change the limit for entries in a jump table if specified by
620 // the sub target, but not at the command line.
621 unsigned MaxJT = STI.getMaximumJumpTableSize();
622 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
623 setMaximumJumpTableSize(MaxJT);
624
625 setHasExtractBitsInsn(true);
626
627 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
628
629 if (Subtarget->hasNEON()) {
630 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
631 // silliness like this:
632 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
633 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
634 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
635 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
636 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
637 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
638 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
639 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
640 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
641 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
642 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
643 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
644 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
645 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
646 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
647 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
648 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
649 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
650 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
651 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
652 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
653 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
654 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
655 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
656 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
657
658 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
659 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
660 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
661 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
662 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
663
664 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
665
666 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
667 // elements smaller than i32, so promote the input to i32 first.
668 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
669 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
670 // i8 vector elements also need promotion to i32 for v8i8
671 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
672 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
673 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
674 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
675 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
676 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
677 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
678 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
679 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
680 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
681 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
682
683 if (Subtarget->hasFullFP16()) {
684 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
685 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
686 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
687 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
688 } else {
689 // when AArch64 doesn't have fullfp16 support, promote the input
690 // to i32 first.
691 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
692 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
693 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
694 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
695 }
696
697 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
698 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
699
700 // AArch64 doesn't have MUL.2d:
701 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
702 // Custom handling for some quad-vector types to detect MULL.
703 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
704 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
705 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
706
707 // Vector reductions
708 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
709 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
710 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
711 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
712 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
713 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
714 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
715 }
716 for (MVT VT : { MVT::v4f16, MVT::v2f32,
717 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
718 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
719 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
720 }
721
722 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
723 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
724 // Likewise, narrowing and extending vector loads/stores aren't handled
725 // directly.
726 for (MVT VT : MVT::vector_valuetypes()) {
727 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
728
729 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
730 setOperationAction(ISD::MULHS, VT, Legal);
731 setOperationAction(ISD::MULHU, VT, Legal);
732 } else {
733 setOperationAction(ISD::MULHS, VT, Expand);
734 setOperationAction(ISD::MULHU, VT, Expand);
735 }
736 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
737 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
738
739 setOperationAction(ISD::BSWAP, VT, Expand);
740 setOperationAction(ISD::CTTZ, VT, Expand);
741
742 for (MVT InnerVT : MVT::vector_valuetypes()) {
743 setTruncStoreAction(VT, InnerVT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
746 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
747 }
748 }
749
750 // AArch64 has implementations of a lot of rounding-like FP operations.
751 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
752 setOperationAction(ISD::FFLOOR, Ty, Legal);
753 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
754 setOperationAction(ISD::FCEIL, Ty, Legal);
755 setOperationAction(ISD::FRINT, Ty, Legal);
756 setOperationAction(ISD::FTRUNC, Ty, Legal);
757 setOperationAction(ISD::FROUND, Ty, Legal);
758 }
759
760 if (Subtarget->hasFullFP16()) {
761 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
762 setOperationAction(ISD::FFLOOR, Ty, Legal);
763 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
764 setOperationAction(ISD::FCEIL, Ty, Legal);
765 setOperationAction(ISD::FRINT, Ty, Legal);
766 setOperationAction(ISD::FTRUNC, Ty, Legal);
767 setOperationAction(ISD::FROUND, Ty, Legal);
768 }
769 }
770
771 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
772 }
773
774 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
775}
776
777void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
778 assert(VT.isVector() && "VT should be a vector type");
779
780 if (VT.isFloatingPoint()) {
781 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
782 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
783 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
784 }
785
786 // Mark vector float intrinsics as expand.
787 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
788 setOperationAction(ISD::FSIN, VT, Expand);
789 setOperationAction(ISD::FCOS, VT, Expand);
790 setOperationAction(ISD::FPOW, VT, Expand);
791 setOperationAction(ISD::FLOG, VT, Expand);
792 setOperationAction(ISD::FLOG2, VT, Expand);
793 setOperationAction(ISD::FLOG10, VT, Expand);
794 setOperationAction(ISD::FEXP, VT, Expand);
795 setOperationAction(ISD::FEXP2, VT, Expand);
796
797 // But we do support custom-lowering for FCOPYSIGN.
798 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
799 }
800
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
802 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
803 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
804 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
805 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
806 setOperationAction(ISD::SRA, VT, Custom);
807 setOperationAction(ISD::SRL, VT, Custom);
808 setOperationAction(ISD::SHL, VT, Custom);
809 setOperationAction(ISD::OR, VT, Custom);
810 setOperationAction(ISD::SETCC, VT, Custom);
811 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
812
813 setOperationAction(ISD::SELECT, VT, Expand);
814 setOperationAction(ISD::SELECT_CC, VT, Expand);
815 setOperationAction(ISD::VSELECT, VT, Expand);
816 for (MVT InnerVT : MVT::all_valuetypes())
817 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
818
819 // CNT supports only B element sizes, then use UADDLP to widen.
820 if (VT != MVT::v8i8 && VT != MVT::v16i8)
821 setOperationAction(ISD::CTPOP, VT, Custom);
822
823 setOperationAction(ISD::UDIV, VT, Expand);
824 setOperationAction(ISD::SDIV, VT, Expand);
825 setOperationAction(ISD::UREM, VT, Expand);
826 setOperationAction(ISD::SREM, VT, Expand);
827 setOperationAction(ISD::FREM, VT, Expand);
828
829 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
830 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
831
832 if (!VT.isFloatingPoint())
833 setOperationAction(ISD::ABS, VT, Legal);
834
835 // [SU][MIN|MAX] are available for all NEON types apart from i64.
836 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
837 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
838 setOperationAction(Opcode, VT, Legal);
839
840 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
841 if (VT.isFloatingPoint() &&
842 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
843 for (unsigned Opcode :
844 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
845 setOperationAction(Opcode, VT, Legal);
846
847 if (Subtarget->isLittleEndian()) {
848 for (unsigned im = (unsigned)ISD::PRE_INC;
849 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
850 setIndexedLoadAction(im, VT, Legal);
851 setIndexedStoreAction(im, VT, Legal);
852 }
853 }
854}
855
856void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
857 addRegisterClass(VT, &AArch64::FPR64RegClass);
858 addTypeForNEON(VT, MVT::v2i32);
859}
860
861void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
862 addRegisterClass(VT, &AArch64::FPR128RegClass);
863 addTypeForNEON(VT, MVT::v4i32);
864}
865
866EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
867 EVT VT) const {
868 if (!VT.isVector())
869 return MVT::i32;
870 return VT.changeVectorElementTypeToInteger();
871}
872
873static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
874 const APInt &Demanded,
875 TargetLowering::TargetLoweringOpt &TLO,
876 unsigned NewOpc) {
877 uint64_t OldImm = Imm, NewImm, Enc;
878 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
879
880 // Return if the immediate is already all zeros, all ones, a bimm32 or a
881 // bimm64.
882 if (Imm == 0 || Imm == Mask ||
883 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
884 return false;
885
886 unsigned EltSize = Size;
887 uint64_t DemandedBits = Demanded.getZExtValue();
888
889 // Clear bits that are not demanded.
890 Imm &= DemandedBits;
891
892 while (true) {
893 // The goal here is to set the non-demanded bits in a way that minimizes
894 // the number of switching between 0 and 1. In order to achieve this goal,
895 // we set the non-demanded bits to the value of the preceding demanded bits.
896 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
897 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
898 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
899 // The final result is 0b11000011.
900 uint64_t NonDemandedBits = ~DemandedBits;
901 uint64_t InvertedImm = ~Imm & DemandedBits;
902 uint64_t RotatedImm =
903 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
904 NonDemandedBits;
905 uint64_t Sum = RotatedImm + NonDemandedBits;
906 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
907 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
908 NewImm = (Imm | Ones) & Mask;
909
910 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
911 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
912 // we halve the element size and continue the search.
913 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
914 break;
915
916 // We cannot shrink the element size any further if it is 2-bits.
917 if (EltSize == 2)
918 return false;
919
920 EltSize /= 2;
921 Mask >>= EltSize;
922 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
923
924 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
925 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
926 return false;
927
928 // Merge the upper and lower halves of Imm and DemandedBits.
929 Imm |= Hi;
930 DemandedBits |= DemandedBitsHi;
931 }
932
933 ++NumOptimizedImms;
934
935 // Replicate the element across the register width.
936 while (EltSize < Size) {
937 NewImm |= NewImm << EltSize;
938 EltSize *= 2;
939 }
940
941 (void)OldImm;
942 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
943 "demanded bits should never be altered");
944 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
945
946 // Create the new constant immediate node.
947 EVT VT = Op.getValueType();
948 SDLoc DL(Op);
949 SDValue New;
950
951 // If the new constant immediate is all-zeros or all-ones, let the target
952 // independent DAG combine optimize this node.
953 if (NewImm == 0 || NewImm == OrigMask) {
954 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
955 TLO.DAG.getConstant(NewImm, DL, VT));
956 // Otherwise, create a machine node so that target independent DAG combine
957 // doesn't undo this optimization.
958 } else {
959 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
960 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
961 New = SDValue(
962 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
963 }
964
965 return TLO.CombineTo(Op, New);
966}
967
968bool AArch64TargetLowering::targetShrinkDemandedConstant(
969 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
970 // Delay this optimization to as late as possible.
971 if (!TLO.LegalOps)
972 return false;
973
974 if (!EnableOptimizeLogicalImm)
975 return false;
976
977 EVT VT = Op.getValueType();
978 if (VT.isVector())
979 return false;
980
981 unsigned Size = VT.getSizeInBits();
982 assert((Size == 32 || Size == 64) &&
983 "i32 or i64 is expected after legalization.");
984
985 // Exit early if we demand all bits.
986 if (Demanded.countPopulation() == Size)
987 return false;
988
989 unsigned NewOpc;
990 switch (Op.getOpcode()) {
991 default:
992 return false;
993 case ISD::AND:
994 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
995 break;
996 case ISD::OR:
997 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
998 break;
999 case ISD::XOR:
1000 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1001 break;
1002 }
1003 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1004 if (!C)
1005 return false;
1006 uint64_t Imm = C->getZExtValue();
1007 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1008}
1009
1010/// computeKnownBitsForTargetNode - Determine which of the bits specified in
1011/// Mask are known to be either zero or one and return them Known.
1012void AArch64TargetLowering::computeKnownBitsForTargetNode(
1013 const SDValue Op, KnownBits &Known,
1014 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1015 switch (Op.getOpcode()) {
1016 default:
1017 break;
1018 case AArch64ISD::CSEL: {
1019 KnownBits Known2;
1020 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1021 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1022 Known.Zero &= Known2.Zero;
1023 Known.One &= Known2.One;
1024 break;
1025 }
1026 case ISD::INTRINSIC_W_CHAIN: {
1027 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1028 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1029 switch (IntID) {
1030 default: return;
1031 case Intrinsic::aarch64_ldaxr:
1032 case Intrinsic::aarch64_ldxr: {
1033 unsigned BitWidth = Known.getBitWidth();
1034 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1035 unsigned MemBits = VT.getScalarSizeInBits();
1036 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1037 return;
1038 }
1039 }
1040 break;
1041 }
1042 case ISD::INTRINSIC_WO_CHAIN:
1043 case ISD::INTRINSIC_VOID: {
1044 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1045 switch (IntNo) {
1046 default:
1047 break;
1048 case Intrinsic::aarch64_neon_umaxv:
1049 case Intrinsic::aarch64_neon_uminv: {
1050 // Figure out the datatype of the vector operand. The UMINV instruction
1051 // will zero extend the result, so we can mark as known zero all the
1052 // bits larger than the element datatype. 32-bit or larget doesn't need
1053 // this as those are legal types and will be handled by isel directly.
1054 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1055 unsigned BitWidth = Known.getBitWidth();
1056 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1057 assert(BitWidth >= 8 && "Unexpected width!");
1058 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1059 Known.Zero |= Mask;
1060 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1061 assert(BitWidth >= 16 && "Unexpected width!");
1062 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1063 Known.Zero |= Mask;
1064 }
1065 break;
1066 } break;
1067 }
1068 }
1069 }
1070}
1071
1072MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1073 EVT) const {
1074 return MVT::i64;
1075}
1076
1077bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1078 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1079 bool *Fast) const {
1080 if (Subtarget->requiresStrictAlign())
1081 return false;
1082
1083 if (Fast) {
1084 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1085 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1086 // See comments in performSTORECombine() for more details about
1087 // these conditions.
1088
1089 // Code that uses clang vector extensions can mark that it
1090 // wants unaligned accesses to be treated as fast by
1091 // underspecifying alignment to be 1 or 2.
1092 Align <= 2 ||
1093
1094 // Disregard v2i64. Memcpy lowering produces those and splitting
1095 // them regresses performance on micro-benchmarks and olden/bh.
1096 VT == MVT::v2i64;
1097 }
1098 return true;
1099}
1100
1101FastISel *
1102AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1103 const TargetLibraryInfo *libInfo) const {
1104 return AArch64::createFastISel(funcInfo, libInfo);
1105}
1106
1107const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1108 switch ((AArch64ISD::NodeType)Opcode) {
1109 case AArch64ISD::FIRST_NUMBER: break;
1110 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1111 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1112 case AArch64ISD::ADR: return "AArch64ISD::ADR";
1113 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1114 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1115 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1116 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1117 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1118 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1119 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1120 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1121 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1122 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1123 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1124 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1125 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1126 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1127 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1128 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1129 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1130 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1131 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1132 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1133 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1134 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1135 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1136 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1137 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1138 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1139 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1140 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1141 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1142 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1143 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1144 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1145 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1146 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1147 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1148 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1149 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1150 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1151 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1152 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1153 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1154 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1155 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1156 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1157 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1158 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1159 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1160 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1161 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1162 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1163 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1164 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1165 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1166 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1167 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1168 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1169 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1170 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1171 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1172 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1173 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1174 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1175 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1176 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1177 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1178 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1179 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1180 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1181 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1182 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1183 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1184 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1185 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1186 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1187 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1188 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1189 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1190 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1191 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1192 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1193 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1194 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1195 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1196 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1197 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1198 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1199 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1200 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1201 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1202 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1203 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1204 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1205 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1206 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1207 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1208 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1209 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1210 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1211 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1212 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1213 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1214 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1215 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1216 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1217 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1218 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1219 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1220 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1221 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1222 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1223 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1224 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1225 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1226 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1227 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1228 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1229 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1230 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1231 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1232 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1233 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1234 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1235 }
1236 return nullptr;
1237}
1238
1239MachineBasicBlock *
1240AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1241 MachineBasicBlock *MBB) const {
1242 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1243 // phi node:
1244
1245 // OrigBB:
1246 // [... previous instrs leading to comparison ...]
1247 // b.ne TrueBB
1248 // b EndBB
1249 // TrueBB:
1250 // ; Fallthrough
1251 // EndBB:
1252 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1253
1254 MachineFunction *MF = MBB->getParent();
1255 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1256 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1257 DebugLoc DL = MI.getDebugLoc();
1258 MachineFunction::iterator It = ++MBB->getIterator();
1259
1260 unsigned DestReg = MI.getOperand(0).getReg();
1261 unsigned IfTrueReg = MI.getOperand(1).getReg();
1262 unsigned IfFalseReg = MI.getOperand(2).getReg();
1263 unsigned CondCode = MI.getOperand(3).getImm();
1264 bool NZCVKilled = MI.getOperand(4).isKill();
1265
1266 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1267 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1268 MF->insert(It, TrueBB);
1269 MF->insert(It, EndBB);
1270
1271 // Transfer rest of current basic-block to EndBB
1272 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1273 MBB->end());
1274 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1275
1276 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1277 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1278 MBB->addSuccessor(TrueBB);
1279 MBB->addSuccessor(EndBB);
1280
1281 // TrueBB falls through to the end.
1282 TrueBB->addSuccessor(EndBB);
1283
1284 if (!NZCVKilled) {
1285 TrueBB->addLiveIn(AArch64::NZCV);
1286 EndBB->addLiveIn(AArch64::NZCV);
1287 }
1288
1289 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1290 .addReg(IfTrueReg)
1291 .addMBB(TrueBB)
1292 .addReg(IfFalseReg)
1293 .addMBB(MBB);
1294
1295 MI.eraseFromParent();
1296 return EndBB;
1297}
1298
1299MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1300 MachineInstr &MI, MachineBasicBlock *BB) const {
1301 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1302 BB->getParent()->getFunction().getPersonalityFn())) &&
1303 "SEH does not use catchret!");
1304 return BB;
1305}
1306
1307MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1308 MachineInstr &MI, MachineBasicBlock *BB) const {
1309 MI.eraseFromParent();
1310 return BB;
1311}
1312
1313MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1314 MachineInstr &MI, MachineBasicBlock *BB) const {
1315 switch (MI.getOpcode()) {
1316 default:
1317#ifndef NDEBUG
1318 MI.dump();
1319#endif
1320 llvm_unreachable("Unexpected instruction for custom inserter!");
1321
1322 case AArch64::F128CSEL:
1323 return EmitF128CSEL(MI, BB);
1324
1325 case TargetOpcode::STACKMAP:
1326 case TargetOpcode::PATCHPOINT:
1327 return emitPatchPoint(MI, BB);
1328
1329 case AArch64::CATCHRET:
1330 return EmitLoweredCatchRet(MI, BB);
1331 case AArch64::CATCHPAD:
1332 return EmitLoweredCatchPad(MI, BB);
1333 }
1334}
1335
1336//===----------------------------------------------------------------------===//
1337// AArch64 Lowering private implementation.
1338//===----------------------------------------------------------------------===//
1339
1340//===----------------------------------------------------------------------===//
1341// Lowering Code
1342//===----------------------------------------------------------------------===//
1343
1344/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1345/// CC
1346static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1347 switch (CC) {
1348 default:
1349 llvm_unreachable("Unknown condition code!");
1350 case ISD::SETNE:
1351 return AArch64CC::NE;
1352 case ISD::SETEQ:
1353 return AArch64CC::EQ;
1354 case ISD::SETGT:
1355 return AArch64CC::GT;
1356 case ISD::SETGE:
1357 return AArch64CC::GE;
1358 case ISD::SETLT:
1359 return AArch64CC::LT;
1360 case ISD::SETLE:
1361 return AArch64CC::LE;
1362 case ISD::SETUGT:
1363 return AArch64CC::HI;
1364 case ISD::SETUGE:
1365 return AArch64CC::HS;
1366 case ISD::SETULT:
1367 return AArch64CC::LO;
1368 case ISD::SETULE:
1369 return AArch64CC::LS;
1370 }
1371}
1372
1373/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1374static void changeFPCCToAArch64CC(ISD::CondCode CC,
1375 AArch64CC::CondCode &CondCode,
1376 AArch64CC::CondCode &CondCode2) {
1377 CondCode2 = AArch64CC::AL;
1378 switch (CC) {
1379 default:
1380 llvm_unreachable("Unknown FP condition!");
1381 case ISD::SETEQ:
1382 case ISD::SETOEQ:
1383 CondCode = AArch64CC::EQ;
1384 break;
1385 case ISD::SETGT:
1386 case ISD::SETOGT:
1387 CondCode = AArch64CC::GT;
1388 break;
1389 case ISD::SETGE:
1390 case ISD::SETOGE:
1391 CondCode = AArch64CC::GE;
1392 break;
1393 case ISD::SETOLT:
1394 CondCode = AArch64CC::MI;
1395 break;
1396 case ISD::SETOLE:
1397 CondCode = AArch64CC::LS;
1398 break;
1399 case ISD::SETONE:
1400 CondCode = AArch64CC::MI;
1401 CondCode2 = AArch64CC::GT;
1402 break;
1403 case ISD::SETO:
1404 CondCode = AArch64CC::VC;
1405 break;
1406 case ISD::SETUO:
1407 CondCode = AArch64CC::VS;
1408 break;
1409 case ISD::SETUEQ:
1410 CondCode = AArch64CC::EQ;
1411 CondCode2 = AArch64CC::VS;
1412 break;
1413 case ISD::SETUGT:
1414 CondCode = AArch64CC::HI;
1415 break;
1416 case ISD::SETUGE:
1417 CondCode = AArch64CC::PL;
1418 break;
1419 case ISD::SETLT:
1420 case ISD::SETULT:
1421 CondCode = AArch64CC::LT;
1422 break;
1423 case ISD::SETLE:
1424 case ISD::SETULE:
1425 CondCode = AArch64CC::LE;
1426 break;
1427 case ISD::SETNE:
1428 case ISD::SETUNE:
1429 CondCode = AArch64CC::NE;
1430 break;
1431 }
1432}
1433
1434/// Convert a DAG fp condition code to an AArch64 CC.
1435/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1436/// should be AND'ed instead of OR'ed.
1437static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1438 AArch64CC::CondCode &CondCode,
1439 AArch64CC::CondCode &CondCode2) {
1440 CondCode2 = AArch64CC::AL;
1441 switch (CC) {
1442 default:
1443 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1444 assert(CondCode2 == AArch64CC::AL);
1445 break;
1446 case ISD::SETONE:
1447 // (a one b)
1448 // == ((a olt b) || (a ogt b))
1449 // == ((a ord b) && (a une b))
1450 CondCode = AArch64CC::VC;
1451 CondCode2 = AArch64CC::NE;
1452 break;
1453 case ISD::SETUEQ:
1454 // (a ueq b)
1455 // == ((a uno b) || (a oeq b))
1456 // == ((a ule b) && (a uge b))
1457 CondCode = AArch64CC::PL;
1458 CondCode2 = AArch64CC::LE;
1459 break;
1460 }
1461}
1462
1463/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1464/// CC usable with the vector instructions. Fewer operations are available
1465/// without a real NZCV register, so we have to use less efficient combinations
1466/// to get the same effect.
1467static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1468 AArch64CC::CondCode &CondCode,
1469 AArch64CC::CondCode &CondCode2,
1470 bool &Invert) {
1471 Invert = false;
1472 switch (CC) {
1473 default:
1474 // Mostly the scalar mappings work fine.
1475 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1476 break;
1477 case ISD::SETUO:
1478 Invert = true;
1479 LLVM_FALLTHROUGH;
1480 case ISD::SETO:
1481 CondCode = AArch64CC::MI;
1482 CondCode2 = AArch64CC::GE;
1483 break;
1484 case ISD::SETUEQ:
1485 case ISD::SETULT:
1486 case ISD::SETULE:
1487 case ISD::SETUGT:
1488 case ISD::SETUGE:
1489 // All of the compare-mask comparisons are ordered, but we can switch
1490 // between the two by a double inversion. E.g. ULE == !OGT.
1491 Invert = true;
1492 changeFPCCToAArch64CC(getSetCCInverse(CC, MVT::f32), CondCode, CondCode2);
1493 break;
1494 }
1495}
1496
1497static bool isLegalArithImmed(uint64_t C) {
1498 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1499 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1500 LLVM_DEBUG(dbgs() << "Is imm " << C
1501 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1502 return IsLegal;
1503}
1504
1505// Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1506// the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1507// can be set differently by this operation. It comes down to whether
1508// "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1509// everything is fine. If not then the optimization is wrong. Thus general
1510// comparisons are only valid if op2 != 0.
1511//
1512// So, finally, the only LLVM-native comparisons that don't mention C and V
1513// are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1514// the absence of information about op2.
1515static bool isCMN(SDValue Op, ISD::CondCode CC) {
1516 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1517 (CC == ISD::SETEQ || CC == ISD::SETNE);
1518}
1519
1520static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1521 const SDLoc &dl, SelectionDAG &DAG) {
1522 EVT VT = LHS.getValueType();
1523 const bool FullFP16 =
1524 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1525
1526 if (VT.isFloatingPoint()) {
1527 assert(VT != MVT::f128);
1528 if (VT == MVT::f16 && !FullFP16) {
1529 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1530 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1531 VT = MVT::f32;
1532 }
1533 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1534 }
1535
1536 // The CMP instruction is just an alias for SUBS, and representing it as
1537 // SUBS means that it's possible to get CSE with subtract operations.
1538 // A later phase can perform the optimization of setting the destination
1539 // register to WZR/XZR if it ends up being unused.
1540 unsigned Opcode = AArch64ISD::SUBS;
1541
1542 if (isCMN(RHS, CC)) {
1543 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1544 Opcode = AArch64ISD::ADDS;
1545 RHS = RHS.getOperand(1);
1546 } else if (isCMN(LHS, CC)) {
1547 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1548 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1549 Opcode = AArch64ISD::ADDS;
1550 LHS = LHS.getOperand(1);
1551 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1552 !isUnsignedIntSetCC(CC)) {
1553 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1554 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1555 // of the signed comparisons.
1556 Opcode = AArch64ISD::ANDS;
1557 RHS = LHS.getOperand(1);
1558 LHS = LHS.getOperand(0);
1559 }
1560
1561 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1562 .getValue(1);
1563}
1564
1565/// \defgroup AArch64CCMP CMP;CCMP matching
1566///
1567/// These functions deal with the formation of CMP;CCMP;... sequences.
1568/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1569/// a comparison. They set the NZCV flags to a predefined value if their
1570/// predicate is false. This allows to express arbitrary conjunctions, for
1571/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1572/// expressed as:
1573/// cmp A
1574/// ccmp B, inv(CB), CA
1575/// check for CB flags
1576///
1577/// This naturally lets us implement chains of AND operations with SETCC
1578/// operands. And we can even implement some other situations by transforming
1579/// them:
1580/// - We can implement (NEG SETCC) i.e. negating a single comparison by
1581/// negating the flags used in a CCMP/FCCMP operations.
1582/// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1583/// by negating the flags we test for afterwards. i.e.
1584/// NEG (CMP CCMP CCCMP ...) can be implemented.
1585/// - Note that we can only ever negate all previously processed results.
1586/// What we can not implement by flipping the flags to test is a negation
1587/// of two sub-trees (because the negation affects all sub-trees emitted so
1588/// far, so the 2nd sub-tree we emit would also affect the first).
1589/// With those tools we can implement some OR operations:
1590/// - (OR (SETCC A) (SETCC B)) can be implemented via:
1591/// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1592/// - After transforming OR to NEG/AND combinations we may be able to use NEG
1593/// elimination rules from earlier to implement the whole thing as a
1594/// CCMP/FCCMP chain.
1595///
1596/// As complete example:
1597/// or (or (setCA (cmp A)) (setCB (cmp B)))
1598/// (and (setCC (cmp C)) (setCD (cmp D)))"
1599/// can be reassociated to:
1600/// or (and (setCC (cmp C)) setCD (cmp D))
1601// (or (setCA (cmp A)) (setCB (cmp B)))
1602/// can be transformed to:
1603/// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1604/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1605/// which can be implemented as:
1606/// cmp C
1607/// ccmp D, inv(CD), CC
1608/// ccmp A, CA, inv(CD)
1609/// ccmp B, CB, inv(CA)
1610/// check for CB flags
1611///
1612/// A counterexample is "or (and A B) (and C D)" which translates to
1613/// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1614/// can only implement 1 of the inner (not) operations, but not both!
1615/// @{
1616
1617/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1618static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1619 ISD::CondCode CC, SDValue CCOp,
1620 AArch64CC::CondCode Predicate,
1621 AArch64CC::CondCode OutCC,
1622 const SDLoc &DL, SelectionDAG &DAG) {
1623 unsigned Opcode = 0;
1624 const bool FullFP16 =
1625 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1626
1627 if (LHS.getValueType().isFloatingPoint()) {
1628 assert(LHS.getValueType() != MVT::f128);
1629 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1630 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1631 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1632 }
1633 Opcode = AArch64ISD::FCCMP;
1634 } else if (RHS.getOpcode() == ISD::SUB) {
1635 SDValue SubOp0 = RHS.getOperand(0);
1636 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1637 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1638 Opcode = AArch64ISD::CCMN;
1639 RHS = RHS.getOperand(1);
1640 }
1641 }
1642 if (Opcode == 0)
1643 Opcode = AArch64ISD::CCMP;
1644
1645 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1646 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1647 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1648 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1649 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1650}
1651
1652/// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1653/// expressed as a conjunction. See \ref AArch64CCMP.
1654/// \param CanNegate Set to true if we can negate the whole sub-tree just by
1655/// changing the conditions on the SETCC tests.
1656/// (this means we can call emitConjunctionRec() with
1657/// Negate==true on this sub-tree)
1658/// \param MustBeFirst Set to true if this subtree needs to be negated and we
1659/// cannot do the negation naturally. We are required to
1660/// emit the subtree first in this case.
1661/// \param WillNegate Is true if are called when the result of this
1662/// subexpression must be negated. This happens when the
1663/// outer expression is an OR. We can use this fact to know
1664/// that we have a double negation (or (or ...) ...) that
1665/// can be implemented for free.
1666static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1667 bool &MustBeFirst, bool WillNegate,
1668 unsigned Depth = 0) {
1669 if (!Val.hasOneUse())
1670 return false;
1671 unsigned Opcode = Val->getOpcode();
1672 if (Opcode == ISD::SETCC) {
1673 if (Val->getOperand(0).getValueType() == MVT::f128)
1674 return false;
1675 CanNegate = true;
1676 MustBeFirst = false;
1677 return true;
1678 }
1679 // Protect against exponential runtime and stack overflow.
1680 if (Depth > 6)
1681 return false;
1682 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1683 bool IsOR = Opcode == ISD::OR;
1684 SDValue O0 = Val->getOperand(0);
1685 SDValue O1 = Val->getOperand(1);
1686 bool CanNegateL;
1687 bool MustBeFirstL;
1688 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1689 return false;
1690 bool CanNegateR;
1691 bool MustBeFirstR;
1692 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1693 return false;
1694
1695 if (MustBeFirstL && MustBeFirstR)
1696 return false;
1697
1698 if (IsOR) {
1699 // For an OR expression we need to be able to naturally negate at least
1700 // one side or we cannot do the transformation at all.
1701 if (!CanNegateL && !CanNegateR)
1702 return false;
1703 // If we the result of the OR will be negated and we can naturally negate
1704 // the leafs, then this sub-tree as a whole negates naturally.
1705 CanNegate = WillNegate && CanNegateL && CanNegateR;
1706 // If we cannot naturally negate the whole sub-tree, then this must be
1707 // emitted first.
1708 MustBeFirst = !CanNegate;
1709 } else {
1710 assert(Opcode == ISD::AND && "Must be OR or AND");
1711 // We cannot naturally negate an AND operation.
1712 CanNegate = false;
1713 MustBeFirst = MustBeFirstL || MustBeFirstR;
1714 }
1715 return true;
1716 }
1717 return false;
1718}
1719
1720/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1721/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1722/// Tries to transform the given i1 producing node @p Val to a series compare
1723/// and conditional compare operations. @returns an NZCV flags producing node
1724/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1725/// transformation was not possible.
1726/// \p Negate is true if we want this sub-tree being negated just by changing
1727/// SETCC conditions.
1728static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1729 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1730 AArch64CC::CondCode Predicate) {
1731 // We're at a tree leaf, produce a conditional comparison operation.
1732 unsigned Opcode = Val->getOpcode();
1733 if (Opcode == ISD::SETCC) {
1734 SDValue LHS = Val->getOperand(0);
1735 SDValue RHS = Val->getOperand(1);
1736 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1737 bool isInteger = LHS.getValueType().isInteger();
1738 if (Negate)
1739 CC = getSetCCInverse(CC, LHS.getValueType());
1740 SDLoc DL(Val);
1741 // Determine OutCC and handle FP special case.
1742 if (isInteger) {
1743 OutCC = changeIntCCToAArch64CC(CC);
1744 } else {
1745 assert(LHS.getValueType().isFloatingPoint());
1746 AArch64CC::CondCode ExtraCC;
1747 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1748 // Some floating point conditions can't be tested with a single condition
1749 // code. Construct an additional comparison in this case.
1750 if (ExtraCC != AArch64CC::AL) {
1751 SDValue ExtraCmp;
1752 if (!CCOp.getNode())
1753 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1754 else
1755 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1756 ExtraCC, DL, DAG);
1757 CCOp = ExtraCmp;
1758 Predicate = ExtraCC;
1759 }
1760 }
1761
1762 // Produce a normal comparison if we are first in the chain
1763 if (!CCOp)
1764 return emitComparison(LHS, RHS, CC, DL, DAG);
1765 // Otherwise produce a ccmp.
1766 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1767 DAG);
1768 }
1769 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1770
1771 bool IsOR = Opcode == ISD::OR;
1772
1773 SDValue LHS = Val->getOperand(0);
1774 bool CanNegateL;
1775 bool MustBeFirstL;
1776 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1777 assert(ValidL && "Valid conjunction/disjunction tree");
1778 (void)ValidL;
1779
1780 SDValue RHS = Val->getOperand(1);
1781 bool CanNegateR;
1782 bool MustBeFirstR;
1783 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1784 assert(ValidR && "Valid conjunction/disjunction tree");
1785 (void)ValidR;
1786
1787 // Swap sub-tree that must come first to the right side.
1788 if (MustBeFirstL) {
1789 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1790 std::swap(LHS, RHS);
1791 std::swap(CanNegateL, CanNegateR);
1792 std::swap(MustBeFirstL, MustBeFirstR);
1793 }
1794
1795 bool NegateR;
1796 bool NegateAfterR;
1797 bool NegateL;
1798 bool NegateAfterAll;
1799 if (Opcode == ISD::OR) {
1800 // Swap the sub-tree that we can negate naturally to the left.
1801 if (!CanNegateL) {
1802 assert(CanNegateR && "at least one side must be negatable");
1803 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1804 assert(!Negate);
1805 std::swap(LHS, RHS);
1806 NegateR = false;
1807 NegateAfterR = true;
1808 } else {
1809 // Negate the left sub-tree if possible, otherwise negate the result.
1810 NegateR = CanNegateR;
1811 NegateAfterR = !CanNegateR;
1812 }
1813 NegateL = true;
1814 NegateAfterAll = !Negate;
1815 } else {
1816 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1817 assert(!Negate && "Valid conjunction/disjunction tree");
1818
1819 NegateL = false;
1820 NegateR = false;
1821 NegateAfterR = false;
1822 NegateAfterAll = false;
1823 }
1824
1825 // Emit sub-trees.
1826 AArch64CC::CondCode RHSCC;
1827 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1828 if (NegateAfterR)
1829 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1830 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1831 if (NegateAfterAll)
1832 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1833 return CmpL;
1834}
1835
1836/// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1837/// In some cases this is even possible with OR operations in the expression.
1838/// See \ref AArch64CCMP.
1839/// \see emitConjunctionRec().
1840static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1841 AArch64CC::CondCode &OutCC) {
1842 bool DummyCanNegate;
1843 bool DummyMustBeFirst;
1844 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
1845 return SDValue();
1846
1847 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1848}
1849
1850/// @}
1851
1852/// Returns how profitable it is to fold a comparison's operand's shift and/or
1853/// extension operations.
1854static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1855 auto isSupportedExtend = [&](SDValue V) {
1856 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1857 return true;
1858
1859 if (V.getOpcode() == ISD::AND)
1860 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1861 uint64_t Mask = MaskCst->getZExtValue();
1862 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1863 }
1864
1865 return false;
1866 };
1867
1868 if (!Op.hasOneUse())
1869 return 0;
1870
1871 if (isSupportedExtend(Op))
1872 return 1;
1873
1874 unsigned Opc = Op.getOpcode();
1875 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1876 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1877 uint64_t Shift = ShiftCst->getZExtValue();
1878 if (isSupportedExtend(Op.getOperand(0)))
1879 return (Shift <= 4) ? 2 : 1;
1880 EVT VT = Op.getValueType();
1881 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1882 return 1;
1883 }
1884
1885 return 0;
1886}
1887
1888static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1889 SDValue &AArch64cc, SelectionDAG &DAG,
1890 const SDLoc &dl) {
1891 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1892 EVT VT = RHS.getValueType();
1893 uint64_t C = RHSC->getZExtValue();
1894 if (!isLegalArithImmed(C)) {
1895 // Constant does not fit, try adjusting it by one?
1896 switch (CC) {
1897 default:
1898 break;
1899 case ISD::SETLT:
1900 case ISD::SETGE:
1901 if ((VT == MVT::i32 && C != 0x80000000 &&
1902 isLegalArithImmed((uint32_t)(C - 1))) ||
1903 (VT == MVT::i64 && C != 0x80000000ULL &&
1904 isLegalArithImmed(C - 1ULL))) {
1905 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1906 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1907 RHS = DAG.getConstant(C, dl, VT);
1908 }
1909 break;
1910 case ISD::SETULT:
1911 case ISD::SETUGE:
1912 if ((VT == MVT::i32 && C != 0 &&
1913 isLegalArithImmed((uint32_t)(C - 1))) ||
1914 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1915 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1916 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1917 RHS = DAG.getConstant(C, dl, VT);
1918 }
1919 break;
1920 case ISD::SETLE:
1921 case ISD::SETGT:
1922 if ((VT == MVT::i32 && C != INT32_MAX &&
1923 isLegalArithImmed((uint32_t)(C + 1))) ||
1924 (VT == MVT::i64 && C != INT64_MAX &&
1925 isLegalArithImmed(C + 1ULL))) {
1926 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1927 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1928 RHS = DAG.getConstant(C, dl, VT);
1929 }
1930 break;
1931 case ISD::SETULE:
1932 case ISD::SETUGT:
1933 if ((VT == MVT::i32 && C != UINT32_MAX &&
1934 isLegalArithImmed((uint32_t)(C + 1))) ||
1935 (VT == MVT::i64 && C != UINT64_MAX &&
1936 isLegalArithImmed(C + 1ULL))) {
1937 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1938 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1939 RHS = DAG.getConstant(C, dl, VT);
1940 }
1941 break;
1942 }
1943 }
1944 }
1945
1946 // Comparisons are canonicalized so that the RHS operand is simpler than the
1947 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1948 // can fold some shift+extend operations on the RHS operand, so swap the
1949 // operands if that can be done.
1950 //
1951 // For example:
1952 // lsl w13, w11, #1
1953 // cmp w13, w12
1954 // can be turned into:
1955 // cmp w12, w11, lsl #1
1956 if (!isa<ConstantSDNode>(RHS) ||
1957 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1958 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1959
1960 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
1961 std::swap(LHS, RHS);
1962 CC = ISD::getSetCCSwappedOperands(CC);
1963 }
1964 }
1965
1966 SDValue Cmp;
1967 AArch64CC::CondCode AArch64CC;
1968 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1969 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1970
1971 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1972 // For the i8 operand, the largest immediate is 255, so this can be easily
1973 // encoded in the compare instruction. For the i16 operand, however, the
1974 // largest immediate cannot be encoded in the compare.
1975 // Therefore, use a sign extending load and cmn to avoid materializing the
1976 // -1 constant. For example,
1977 // movz w1, #65535
1978 // ldrh w0, [x0, #0]
1979 // cmp w0, w1
1980 // >
1981 // ldrsh w0, [x0, #0]
1982 // cmn w0, #1
1983 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1984 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1985 // ensure both the LHS and RHS are truly zero extended and to make sure the
1986 // transformation is profitable.
1987 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1988 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1989 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1990 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1991 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1992 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1993 SDValue SExt =
1994 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1995 DAG.getValueType(MVT::i16));
1996 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1997 RHS.getValueType()),
1998 CC, dl, DAG);
1999 AArch64CC = changeIntCCToAArch64CC(CC);
2000 }
2001 }
2002
2003 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2004 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2005 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2006 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2007 }
2008 }
2009 }
2010
2011 if (!Cmp) {
2012 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2013 AArch64CC = changeIntCCToAArch64CC(CC);
2014 }
2015 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2016 return Cmp;
2017}
2018
2019static std::pair<SDValue, SDValue>
2020getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2021 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2022 "Unsupported value type");
2023 SDValue Value, Overflow;
2024 SDLoc DL(Op);
2025 SDValue LHS = Op.getOperand(0);
2026 SDValue RHS = Op.getOperand(1);
2027 unsigned Opc = 0;
2028 switch (Op.getOpcode()) {
2029 default:
2030 llvm_unreachable("Unknown overflow instruction!");
2031 case ISD::SADDO:
2032 Opc = AArch64ISD::ADDS;
2033 CC = AArch64CC::VS;
2034 break;
2035 case ISD::UADDO:
2036 Opc = AArch64ISD::ADDS;
2037 CC = AArch64CC::HS;
2038 break;
2039 case ISD::SSUBO:
2040 Opc = AArch64ISD::SUBS;
2041 CC = AArch64CC::VS;
2042 break;
2043 case ISD::USUBO:
2044 Opc = AArch64ISD::SUBS;
2045 CC = AArch64CC::LO;
2046 break;
2047 // Multiply needs a little bit extra work.
2048 case ISD::SMULO:
2049 case ISD::UMULO: {
2050 CC = AArch64CC::NE;
2051 bool IsSigned = Op.getOpcode() == ISD::SMULO;
2052 if (Op.getValueType() == MVT::i32) {
2053 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2054 // For a 32 bit multiply with overflow check we want the instruction
2055 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2056 // need to generate the following pattern:
2057 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2058 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2059 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2060 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2061 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2062 DAG.getConstant(0, DL, MVT::i64));
2063 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2064 // operation. We need to clear out the upper 32 bits, because we used a
2065 // widening multiply that wrote all 64 bits. In the end this should be a
2066 // noop.
2067 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2068 if (IsSigned) {
2069 // The signed overflow check requires more than just a simple check for
2070 // any bit set in the upper 32 bits of the result. These bits could be
2071 // just the sign bits of a negative number. To perform the overflow
2072 // check we have to arithmetic shift right the 32nd bit of the result by
2073 // 31 bits. Then we compare the result to the upper 32 bits.
2074 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2075 DAG.getConstant(32, DL, MVT::i64));
2076 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2077 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2078 DAG.getConstant(31, DL, MVT::i64));
2079 // It is important that LowerBits is last, otherwise the arithmetic
2080 // shift will not be folded into the compare (SUBS).
2081 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2082 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2083 .getValue(1);
2084 } else {
2085 // The overflow check for unsigned multiply is easy. We only need to
2086 // check if any of the upper 32 bits are set. This can be done with a
2087 // CMP (shifted register). For that we need to generate the following
2088 // pattern:
2089 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2090 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2091 DAG.getConstant(32, DL, MVT::i64));
2092 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2093 Overflow =
2094 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2095 DAG.getConstant(0, DL, MVT::i64),
2096 UpperBits).getValue(1);
2097 }
2098 break;
2099 }
2100 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2101 // For the 64 bit multiply
2102 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2103 if (IsSigned) {
2104 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2105 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2106 DAG.getConstant(63, DL, MVT::i64));
2107 // It is important that LowerBits is last, otherwise the arithmetic
2108 // shift will not be folded into the compare (SUBS).
2109 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2110 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2111 .getValue(1);
2112 } else {
2113 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2114 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2115 Overflow =
2116 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2117 DAG.getConstant(0, DL, MVT::i64),
2118 UpperBits).getValue(1);
2119 }
2120 break;
2121 }
2122 } // switch (...)
2123
2124 if (Opc) {
2125 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2126
2127 // Emit the AArch64 operation with overflow check.
2128 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2129 Overflow = Value.getValue(1);
2130 }
2131 return std::make_pair(Value, Overflow);
2132}
2133
2134SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2135 RTLIB::Libcall Call) const {
2136 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2137 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
2138}
2139
2140// Returns true if the given Op is the overflow flag result of an overflow
2141// intrinsic operation.
2142static bool isOverflowIntrOpRes(SDValue Op) {
2143 unsigned Opc = Op.getOpcode();
2144 return (Op.getResNo() == 1 &&
2145 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2146 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2147}
2148
2149static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2150 SDValue Sel = Op.getOperand(0);
2151 SDValue Other = Op.getOperand(1);
2152 SDLoc dl(Sel);
2153
2154 // If the operand is an overflow checking operation, invert the condition
2155 // code and kill the Not operation. I.e., transform:
2156 // (xor (overflow_op_bool, 1))
2157 // -->
2158 // (csel 1, 0, invert(cc), overflow_op_bool)
2159 // ... which later gets transformed to just a cset instruction with an
2160 // inverted condition code, rather than a cset + eor sequence.
2161 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2162 // Only lower legal XALUO ops.
2163 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2164 return SDValue();
2165
2166 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2167 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2168 AArch64CC::CondCode CC;
2169 SDValue Value, Overflow;
2170 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2171 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2172 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2173 CCVal, Overflow);
2174 }
2175 // If neither operand is a SELECT_CC, give up.
2176 if (Sel.getOpcode() != ISD::SELECT_CC)
2177 std::swap(Sel, Other);
2178 if (Sel.getOpcode() != ISD::SELECT_CC)
2179 return Op;
2180
2181 // The folding we want to perform is:
2182 // (xor x, (select_cc a, b, cc, 0, -1) )
2183 // -->
2184 // (csel x, (xor x, -1), cc ...)
2185 //
2186 // The latter will get matched to a CSINV instruction.
2187
2188 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2189 SDValue LHS = Sel.getOperand(0);
2190 SDValue RHS = Sel.getOperand(1);
2191 SDValue TVal = Sel.getOperand(2);
2192 SDValue FVal = Sel.getOperand(3);
2193
2194 // FIXME: This could be generalized to non-integer comparisons.
2195 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2196 return Op;
2197
2198 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2199 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2200
2201 // The values aren't constants, this isn't the pattern we're looking for.
2202 if (!CFVal || !CTVal)
2203 return Op;
2204
2205 // We can commute the SELECT_CC by inverting the condition. This
2206 // might be needed to make this fit into a CSINV pattern.
2207 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2208 std::swap(TVal, FVal);
2209 std::swap(CTVal, CFVal);
2210 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2211 }
2212
2213 // If the constants line up, perform the transform!
2214 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2215 SDValue CCVal;
2216 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2217
2218 FVal = Other;
2219 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2220 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2221
2222 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2223 CCVal, Cmp);
2224 }
2225
2226 return Op;
2227}
2228
2229static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2230 EVT VT = Op.getValueType();
2231
2232 // Let legalize expand this if it isn't a legal type yet.
2233 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2234 return SDValue();
2235
2236 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2237
2238 unsigned Opc;
2239 bool ExtraOp = false;
2240 switch (Op.getOpcode()) {
2241 default:
2242 llvm_unreachable("Invalid code");
2243 case ISD::ADDC:
2244 Opc = AArch64ISD::ADDS;
2245 break;
2246 case ISD::SUBC:
2247 Opc = AArch64ISD::SUBS;
2248 break;
2249 case ISD::ADDE:
2250 Opc = AArch64ISD::ADCS;
2251 ExtraOp = true;
2252 break;
2253 case ISD::SUBE:
2254 Opc = AArch64ISD::SBCS;
2255 ExtraOp = true;
2256 break;
2257 }
2258
2259 if (!ExtraOp)
2260 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2261 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2262 Op.getOperand(2));
2263}
2264
2265static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2266 // Let legalize expand this if it isn't a legal type yet.
2267 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2268 return SDValue();
2269
2270 SDLoc dl(Op);
2271 AArch64CC::CondCode CC;
2272 // The actual operation that sets the overflow or carry flag.
2273 SDValue Value, Overflow;
2274 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2275
2276 // We use 0 and 1 as false and true values.
2277 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2278 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2279
2280 // We use an inverted condition, because the conditional select is inverted
2281 // too. This will allow it to be selected to a single instruction:
2282 // CSINC Wd, WZR, WZR, invert(cond).
2283 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2284 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2285 CCVal, Overflow);
2286
2287 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2288 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2289}
2290
2291// Prefetch operands are:
2292// 1: Address to prefetch
2293// 2: bool isWrite
2294// 3: int locality (0 = no locality ... 3 = extreme locality)
2295// 4: bool isDataCache
2296static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2297 SDLoc DL(Op);
2298 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2299 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2300 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2301
2302 bool IsStream = !Locality;
2303 // When the locality number is set
2304 if (Locality) {
2305 // The front-end should have filtered out the out-of-range values
2306 assert(Locality <= 3 && "Prefetch locality out-of-range");
2307 // The locality degree is the opposite of the cache speed.
2308 // Put the number the other way around.
2309 // The encoding starts at 0 for level 1
2310 Locality = 3 - Locality;
2311 }
2312
2313 // built the mask value encoding the expected behavior.
2314 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2315 (!IsData << 3) | // IsDataCache bit
2316 (Locality << 1) | // Cache level bits
2317 (unsigned)IsStream; // Stream bit
2318 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2319 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2320}
2321
2322SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2323 SelectionDAG &DAG) const {
2324 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2325
2326 RTLIB::Libcall LC;
2327 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2328
2329 return LowerF128Call(Op, DAG, LC);
2330}
2331
2332SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2333 SelectionDAG &DAG) const {
2334 if (Op.getOperand(0).getValueType() != MVT::f128) {
2335 // It's legal except when f128 is involved
2336 return Op;
2337 }
2338
2339 RTLIB::Libcall LC;
2340 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2341
2342 // FP_ROUND node has a second operand indicating whether it is known to be
2343 // precise. That doesn't take part in the LibCall so we can't directly use
2344 // LowerF128Call.
2345 SDValue SrcVal = Op.getOperand(0);
2346 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2347 SDLoc(Op)).first;
2348}
2349
2350SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2351 SelectionDAG &DAG) const {
2352 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2353 // Any additional optimization in this function should be recorded
2354 // in the cost tables.
2355 EVT InVT = Op.getOperand(0).getValueType();
2356 EVT VT = Op.getValueType();
2357 unsigned NumElts = InVT.getVectorNumElements();
2358
2359 // f16 conversions are promoted to f32 when full fp16 is not supported.
2360 if (InVT.getVectorElementType() == MVT::f16 &&
2361 !Subtarget->hasFullFP16()) {
2362 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2363 SDLoc dl(Op);
2364 return DAG.getNode(
2365 Op.getOpcode(), dl, Op.getValueType(),
2366 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2367 }
2368
2369 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2370 SDLoc dl(Op);
2371 SDValue Cv =
2372 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2373 Op.getOperand(0));
2374 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2375 }
2376
2377 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2378 SDLoc dl(Op);
2379 MVT ExtVT =
2380 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2381 VT.getVectorNumElements());
2382 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2383 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2384 }
2385
2386 // Type changing conversions are illegal.
2387 return Op;
2388}
2389
2390SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2391 SelectionDAG &DAG) const {
2392 if (Op.getOperand(0).getValueType().isVector())
2393 return LowerVectorFP_TO_INT(Op, DAG);
2394
2395 // f16 conversions are promoted to f32 when full fp16 is not supported.
2396 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2397 !Subtarget->hasFullFP16()) {
2398 SDLoc dl(Op);
2399 return DAG.getNode(
2400 Op.getOpcode(), dl, Op.getValueType(),
2401 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2402 }
2403
2404 if (Op.getOperand(0).getValueType() != MVT::f128) {
2405 // It's legal except when f128 is involved
2406 return Op;
2407 }
2408
2409 RTLIB::Libcall LC;
2410 if (Op.getOpcode() == ISD::FP_TO_SINT)
2411 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2412 else
2413 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2414
2415 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2416 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2417}
2418
2419static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2420 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2421 // Any additional optimization in this function should be recorded
2422 // in the cost tables.
2423 EVT VT = Op.getValueType();
2424 SDLoc dl(Op);
2425 SDValue In = Op.getOperand(0);
2426 EVT InVT = In.getValueType();
2427
2428 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2429 MVT CastVT =
2430 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2431 InVT.getVectorNumElements());
2432 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2433 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2434 }
2435
2436 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2437 unsigned CastOpc =
2438 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2439 EVT CastVT = VT.changeVectorElementTypeToInteger();
2440 In = DAG.getNode(CastOpc, dl, CastVT, In);
2441 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2442 }
2443
2444 return Op;
2445}
2446
2447SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2448 SelectionDAG &DAG) const {
2449 if (Op.getValueType().isVector())
2450 return LowerVectorINT_TO_FP(Op, DAG);
2451
2452 // f16 conversions are promoted to f32 when full fp16 is not supported.
2453 if (Op.getValueType() == MVT::f16 &&
2454 !Subtarget->hasFullFP16()) {
2455 SDLoc dl(Op);
2456 return DAG.getNode(
2457 ISD::FP_ROUND, dl, MVT::f16,
2458 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2459 DAG.getIntPtrConstant(0, dl));
2460 }
2461
2462 // i128 conversions are libcalls.
2463 if (Op.getOperand(0).getValueType() == MVT::i128)
2464 return SDValue();
2465
2466 // Other conversions are legal, unless it's to the completely software-based
2467 // fp128.
2468 if (Op.getValueType() != MVT::f128)
2469 return Op;
2470
2471 RTLIB::Libcall LC;
2472 if (Op.getOpcode() == ISD::SINT_TO_FP)
2473 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2474 else
2475 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2476
2477 return LowerF128Call(Op, DAG, LC);
2478}
2479
2480SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2481 SelectionDAG &DAG) const {
2482 // For iOS, we want to call an alternative entry point: __sincos_stret,
2483 // which returns the values in two S / D registers.
2484 SDLoc dl(Op);
2485 SDValue Arg = Op.getOperand(0);
2486 EVT ArgVT = Arg.getValueType();
2487 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2488
2489 ArgListTy Args;
2490 ArgListEntry Entry;
2491
2492 Entry.Node = Arg;
2493 Entry.Ty = ArgTy;
2494 Entry.IsSExt = false;
2495 Entry.IsZExt = false;
2496 Args.push_back(Entry);
2497
2498 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2499 : RTLIB::SINCOS_STRET_F32;
2500 const char *LibcallName = getLibcallName(LC);
2501 SDValue Callee = DAG.getExternalFunctionSymbol(LibcallName);
2502
2503 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2504 TargetLowering::CallLoweringInfo CLI(DAG);
2505 CLI.setDebugLoc(dl)
2506 .setChain(DAG.getEntryNode())
2507 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2508
2509 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2510 return CallResult.first;
2511}
2512
2513static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2514 if (Op.getValueType() != MVT::f16)
2515 return SDValue();
2516
2517 assert(Op.getOperand(0).getValueType() == MVT::i16);
2518 SDLoc DL(Op);
2519
2520 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2521 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2522 return SDValue(
2523 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2524 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2525 0);
2526}
2527
2528static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2529 if (OrigVT.getSizeInBits() >= 64)
2530 return OrigVT;
2531
2532 assert(OrigVT.isSimple() && "Expecting a simple value type");
2533
2534 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2535 switch (OrigSimpleTy) {
2536 default: llvm_unreachable("Unexpected Vector Type");
2537 case MVT::v2i8:
2538 case MVT::v2i16:
2539 return MVT::v2i32;
2540 case MVT::v4i8:
2541 return MVT::v4i16;
2542 }
2543}
2544
2545static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2546 const EVT &OrigTy,
2547 const EVT &ExtTy,
2548 unsigned ExtOpcode) {
2549 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2550 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2551 // 64-bits we need to insert a new extension so that it will be 64-bits.
2552 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2553 if (OrigTy.getSizeInBits() >= 64)
2554 return N;
2555
2556 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2557 EVT NewVT = getExtensionTo64Bits(OrigTy);
2558
2559 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2560}
2561
2562static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2563 bool isSigned) {
2564 EVT VT = N->getValueType(0);
2565
2566 if (N->getOpcode() != ISD::BUILD_VECTOR)
2567 return false;
2568
2569 for (const SDValue &Elt : N->op_values()) {
2570 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2571 unsigned EltSize = VT.getScalarSizeInBits();
2572 unsigned HalfSize = EltSize / 2;
2573 if (isSigned) {
2574 if (!isIntN(HalfSize, C->getSExtValue()))
2575 return false;
2576 } else {
2577 if (!isUIntN(HalfSize, C->getZExtValue()))
2578 return false;
2579 }
2580 continue;
2581 }
2582 return false;
2583 }
2584
2585 return true;
2586}
2587
2588static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2589 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2590 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2591 N->getOperand(0)->getValueType(0),
2592 N->getValueType(0),
2593 N->getOpcode());
2594
2595 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2596 EVT VT = N->getValueType(0);
2597 SDLoc dl(N);
2598 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2599 unsigned NumElts = VT.getVectorNumElements();
2600 MVT TruncVT = MVT::getIntegerVT(EltSize);
2601 SmallVector<SDValue, 8> Ops;
2602 for (unsigned i = 0; i != NumElts; ++i) {
2603 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2604 const APInt &CInt = C->getAPIntValue();
2605 // Element types smaller than 32 bits are not legal, so use i32 elements.
2606 // The values are implicitly truncated so sext vs. zext doesn't matter.
2607 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2608 }
2609 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2610}
2611
2612static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2613 return N->getOpcode() == ISD::SIGN_EXTEND ||
2614 isExtendedBUILD_VECTOR(N, DAG, true);
2615}
2616
2617static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2618 return N->getOpcode() == ISD::ZERO_EXTEND ||
2619 isExtendedBUILD_VECTOR(N, DAG, false);
2620}
2621
2622static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2623 unsigned Opcode = N->getOpcode();
2624 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2625 SDNode *N0 = N->getOperand(0).getNode();
2626 SDNode *N1 = N->getOperand(1).getNode();
2627 return N0->hasOneUse() && N1->hasOneUse() &&
2628 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2629 }
2630 return false;
2631}
2632
2633static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2634 unsigned Opcode = N->getOpcode();
2635 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2636 SDNode *N0 = N->getOperand(0).getNode();
2637 SDNode *N1 = N->getOperand(1).getNode();
2638 return N0->hasOneUse() && N1->hasOneUse() &&
2639 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2640 }
2641 return false;
2642}
2643
2644SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2645 SelectionDAG &DAG) const {
2646 // The rounding mode is in bits 23:22 of the FPSCR.
2647 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2648 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2649 // so that the shift + and get folded into a bitfield extract.
2650 SDLoc dl(Op);
2651
2652 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2653 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2654 MVT::i64));
2655 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2656 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2657 DAG.getConstant(1U << 22, dl, MVT::i32));
2658 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2659 DAG.getConstant(22, dl, MVT::i32));
2660 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2661 DAG.getConstant(3, dl, MVT::i32));
2662}
2663
2664static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2665 // Multiplications are only custom-lowered for 128-bit vectors so that
2666 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2667 EVT VT = Op.getValueType();
2668 assert(VT.is128BitVector() && VT.isInteger() &&
2669 "unexpected type for custom-lowering ISD::MUL");
2670 SDNode *N0 = Op.getOperand(0).getNode();
2671 SDNode *N1 = Op.getOperand(1).getNode();
2672 unsigned NewOpc = 0;
2673 bool isMLA = false;
2674 bool isN0SExt = isSignExtended(N0, DAG);
2675 bool isN1SExt = isSignExtended(N1, DAG);
2676 if (isN0SExt && isN1SExt)
2677 NewOpc = AArch64ISD::SMULL;
2678 else {
2679 bool isN0ZExt = isZeroExtended(N0, DAG);
2680 bool isN1ZExt = isZeroExtended(N1, DAG);
2681 if (isN0ZExt && isN1ZExt)
2682 NewOpc = AArch64ISD::UMULL;
2683 else if (isN1SExt || isN1ZExt) {
2684 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2685 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2686 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2687 NewOpc = AArch64ISD::SMULL;
2688 isMLA = true;
2689 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2690 NewOpc = AArch64ISD::UMULL;
2691 isMLA = true;
2692 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2693 std::swap(N0, N1);
2694 NewOpc = AArch64ISD::UMULL;
2695 isMLA = true;
2696 }
2697 }
2698
2699 if (!NewOpc) {
2700 if (VT == MVT::v2i64)
2701 // Fall through to expand this. It is not legal.
2702 return SDValue();
2703 else
2704 // Other vector multiplications are legal.
2705 return Op;
2706 }
2707 }
2708
2709 // Legalize to a S/UMULL instruction
2710 SDLoc DL(Op);
2711 SDValue Op0;
2712 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2713 if (!isMLA) {
2714 Op0 = skipExtensionForVectorMULL(N0, DAG);
2715 assert(Op0.getValueType().is64BitVector() &&
2716 Op1.getValueType().is64BitVector() &&
2717 "unexpected types for extended operands to VMULL");
2718 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2719 }
2720 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2721 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2722 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2723 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2724 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2725 EVT Op1VT = Op1.getValueType();
2726 return DAG.getNode(N0->getOpcode(), DL, VT,
2727 DAG.getNode(NewOpc, DL, VT,
2728 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2729 DAG.getNode(NewOpc, DL, VT,
2730 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2731}
2732
2733SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2734 SelectionDAG &DAG) const {
2735 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2736 SDLoc dl(Op);
2737 switch (IntNo) {
2738 default: return SDValue(); // Don't custom lower most intrinsics.
2739 case Intrinsic::thread_pointer: {
2740 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2741 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2742 }
2743 case Intrinsic::aarch64_neon_abs: {
2744 EVT Ty = Op.getValueType();
2745 if (Ty == MVT::i64) {
2746 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2747 Op.getOperand(1));
2748 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2749 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2750 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2751 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2752 } else {
2753 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2754 }
2755 }
2756 case Intrinsic::aarch64_neon_smax:
2757 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2758 Op.getOperand(1), Op.getOperand(2));
2759 case Intrinsic::aarch64_neon_umax:
2760 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2761 Op.getOperand(1), Op.getOperand(2));
2762 case Intrinsic::aarch64_neon_smin:
2763 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2764 Op.getOperand(1), Op.getOperand(2));
2765 case Intrinsic::aarch64_neon_umin:
2766 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2767 Op.getOperand(1), Op.getOperand(2));
2768
2769 case Intrinsic::localaddress: {
2770 const auto &MF = DAG.getMachineFunction();
2771 const auto *RegInfo = Subtarget->getRegisterInfo();
2772 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
2773 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2774 Op.getSimpleValueType());
2775 }
2776
2777 case Intrinsic::eh_recoverfp: {
2778 // FIXME: This needs to be implemented to correctly handle highly aligned
2779 // stack objects. For now we simply return the incoming FP. Refer D53541
2780 // for more details.
2781 SDValue FnOp = Op.getOperand(1);
2782 SDValue IncomingFPOp = Op.getOperand(2);
2783 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2784 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2785 if (!Fn)
2786 report_fatal_error(
2787 "llvm.eh.recoverfp must take a function as the first argument");
2788 return IncomingFPOp;
2789 }
2790 }
2791}
2792
2793// Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2794static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2795 EVT VT, EVT MemVT,
2796 SelectionDAG &DAG) {
2797 assert(VT.isVector() && "VT should be a vector type");
2798 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2799
2800 SDValue Value = ST->getValue();
2801
2802 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2803 // the word lane which represent the v4i8 subvector. It optimizes the store
2804 // to:
2805 //
2806 // xtn v0.8b, v0.8h
2807 // str s0, [x0]
2808
2809 SDValue Undef = DAG.getUNDEF(MVT::i16);
2810 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2811 {Undef, Undef, Undef, Undef});
2812
2813 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2814 Value, UndefVec);
2815 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2816
2817 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2818 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2819 Trunc, DAG.getConstant(0, DL, MVT::i64));
2820
2821 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2822 ST->getBasePtr(), ST->getMemOperand());
2823}
2824
2825// Custom lowering for any store, vector or scalar and/or default or with
2826// a truncate operations. Currently only custom lower truncate operation
2827// from vector v4i16 to v4i8.
2828SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2829 SelectionDAG &DAG) const {
2830 SDLoc Dl(Op);
2831 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2832 assert (StoreNode && "Can only custom lower store nodes");
2833
2834 SDValue Value = StoreNode->getValue();
2835
2836 EVT VT = Value.getValueType();
2837 EVT MemVT = StoreNode->getMemoryVT();
2838
2839 assert (VT.isVector() && "Can only custom lower vector store types");
2840
2841 unsigned AS = StoreNode->getAddressSpace();
2842 unsigned Align = StoreNode->getAlignment();
2843 if (Align < MemVT.getStoreSize() &&
2844 !allowsMisalignedMemoryAccesses(
2845 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
2846 return scalarizeVectorStore(StoreNode, DAG);
2847 }
2848
2849 if (StoreNode->isTruncatingStore()) {
2850 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2851 }
2852
2853 return SDValue();
2854}
2855
2856SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2857 SelectionDAG &DAG) const {
2858 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2859 LLVM_DEBUG(Op.dump());
2860
2861 switch (Op.getOpcode()) {
2862 default:
2863 llvm_unreachable("unimplemented operand");
2864 return SDValue();
2865 case ISD::BITCAST:
2866 return LowerBITCAST(Op, DAG);
2867 case ISD::GlobalAddress:
2868 return LowerGlobalAddress(Op, DAG);
2869 case ISD::GlobalTLSAddress:
2870 return LowerGlobalTLSAddress(Op, DAG);
2871 case ISD::SETCC:
2872 return LowerSETCC(Op, DAG);
2873 case ISD::BR_CC:
2874 return LowerBR_CC(Op, DAG);
2875 case ISD::SELECT:
2876 return LowerSELECT(Op, DAG);
2877 case ISD::SELECT_CC:
2878 return LowerSELECT_CC(Op, DAG);
2879 case ISD::JumpTable:
2880 return LowerJumpTable(Op, DAG);
2881 case ISD::BR_JT:
2882 return LowerBR_JT(Op, DAG);
2883 case ISD::ConstantPool:
2884 return LowerConstantPool(Op, DAG);
2885 case ISD::BlockAddress:
2886 return LowerBlockAddress(Op, DAG);
2887 case ISD::VASTART:
2888 return LowerVASTART(Op, DAG);
2889 case ISD::VACOPY:
2890 return LowerVACOPY(Op, DAG);
2891 case ISD::VAARG:
2892 return LowerVAARG(Op, DAG);
2893 case ISD::ADDC:
2894 case ISD::ADDE:
2895 case ISD::SUBC:
2896 case ISD::SUBE:
2897 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2898 case ISD::SADDO:
2899 case ISD::UADDO:
2900 case ISD::SSUBO:
2901 case ISD::USUBO:
2902 case ISD::SMULO:
2903 case ISD::UMULO:
2904 return LowerXALUO(Op, DAG);
2905 case ISD::FADD:
2906 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2907 case ISD::FSUB:
2908 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2909 case ISD::FMUL:
2910 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2911 case ISD::FDIV:
2912 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2913 case ISD::FP_ROUND:
2914 return LowerFP_ROUND(Op, DAG);
2915 case ISD::FP_EXTEND:
2916 return LowerFP_EXTEND(Op, DAG);
2917 case ISD::FRAMEADDR:
2918 return LowerFRAMEADDR(Op, DAG);
2919 case ISD::SPONENTRY:
2920 return LowerSPONENTRY(Op, DAG);
2921 case ISD::RETURNADDR:
2922 return LowerRETURNADDR(Op, DAG);
2923 case ISD::ADDROFRETURNADDR:
2924 return LowerADDROFRETURNADDR(Op, DAG);
2925 case ISD::INSERT_VECTOR_ELT:
2926 return LowerINSERT_VECTOR_ELT(Op, DAG);
2927 case ISD::EXTRACT_VECTOR_ELT:
2928 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2929 case ISD::BUILD_VECTOR:
2930 return LowerBUILD_VECTOR(Op, DAG);
2931 case ISD::VECTOR_SHUFFLE:
2932 return LowerVECTOR_SHUFFLE(Op, DAG);
2933 case ISD::EXTRACT_SUBVECTOR:
2934 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2935 case ISD::SRA:
2936 case ISD::SRL:
2937 case ISD::SHL:
2938 return LowerVectorSRA_SRL_SHL(Op, DAG);
2939 case ISD::SHL_PARTS:
2940 return LowerShiftLeftParts(Op, DAG);
2941 case ISD::SRL_PARTS:
2942 case ISD::SRA_PARTS:
2943 return LowerShiftRightParts(Op, DAG);
2944 case ISD::CTPOP:
2945 return LowerCTPOP(Op, DAG);
2946 case ISD::FCOPYSIGN:
2947 return LowerFCOPYSIGN(Op, DAG);
2948 case ISD::OR:
2949 return LowerVectorOR(Op, DAG);
2950 case ISD::XOR:
2951 return LowerXOR(Op, DAG);
2952 case ISD::PREFETCH:
2953 return LowerPREFETCH(Op, DAG);
2954 case ISD::SINT_TO_FP:
2955 case ISD::UINT_TO_FP:
2956 return LowerINT_TO_FP(Op, DAG);
2957 case ISD::FP_TO_SINT:
2958 case ISD::FP_TO_UINT:
2959 return LowerFP_TO_INT(Op, DAG);
2960 case ISD::FSINCOS:
2961 return LowerFSINCOS(Op, DAG);
2962 case ISD::FLT_ROUNDS_:
2963 return LowerFLT_ROUNDS_(Op, DAG);
2964 case ISD::MUL:
2965 return LowerMUL(Op, DAG);
2966 case ISD::INTRINSIC_WO_CHAIN:
2967 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2968 case ISD::STORE:
2969 return LowerSTORE(Op, DAG);
2970 case ISD::VECREDUCE_ADD:
2971 case ISD::VECREDUCE_SMAX:
2972 case ISD::VECREDUCE_SMIN:
2973 case ISD::VECREDUCE_UMAX:
2974 case ISD::VECREDUCE_UMIN:
2975 case ISD::VECREDUCE_FMAX:
2976 case ISD::VECREDUCE_FMIN:
2977 return LowerVECREDUCE(Op, DAG);
2978 case ISD::ATOMIC_LOAD_SUB:
2979 return LowerATOMIC_LOAD_SUB(Op, DAG);
2980 case ISD::ATOMIC_LOAD_AND:
2981 return LowerATOMIC_LOAD_AND(Op, DAG);
2982 case ISD::DYNAMIC_STACKALLOC:
2983 return LowerDYNAMIC_STACKALLOC(Op, DAG);
2984 }
2985}
2986
2987//===----------------------------------------------------------------------===//
2988// Calling Convention Implementation
2989//===----------------------------------------------------------------------===//
2990
2991/// Selects the correct CCAssignFn for a given CallingConvention value.
2992CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2993 bool IsVarArg) const {
2994 switch (CC) {
2995 default:
2996 report_fatal_error("Unsupported calling convention.");
2997 case CallingConv::WebKit_JS:
2998 return CC_AArch64_WebKit_JS;
2999 case CallingConv::GHC:
3000 return CC_AArch64_GHC;
3001 case CallingConv::C:
3002 case CallingConv::Fast:
3003 case CallingConv::PreserveMost:
3004 case CallingConv::CXX_FAST_TLS:
3005 case CallingConv::Swift:
3006 if (Subtarget->isTargetWindows() && IsVarArg)
3007 return CC_AArch64_Win64_VarArg;
3008 if (!Subtarget->isTargetDarwin())
3009 return CC_AArch64_AAPCS;
3010 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
3011 case CallingConv::Win64:
3012 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3013 case CallingConv::AArch64_VectorCall:
3014 return CC_AArch64_AAPCS;
3015 }
3016}
3017
3018CCAssignFn *
3019AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3020 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3021 : RetCC_AArch64_AAPCS;
3022}
3023
3024SDValue AArch64TargetLowering::LowerFormalArguments(
3025 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3026 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3027 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3028 MachineFunction &MF = DAG.getMachineFunction();
3029 MachineFrameInfo &MFI = MF.getFrameInfo();
3030 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3031
3032 // Assign locations to all of the incoming arguments.
3033 SmallVector<CCValAssign, 16> ArgLocs;
3034 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3035 *DAG.getContext());
3036
3037 // At this point, Ins[].VT may already be promoted to i32. To correctly
3038 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3039 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3040 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3041 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3042 // LocVT.
3043 unsigned NumArgs = Ins.size();
3044 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3045 unsigned CurArgIdx = 0;
3046 for (unsigned i = 0; i != NumArgs; ++i) {
3047 MVT ValVT = Ins[i].VT;
3048 if (Ins[i].isOrigArg()) {
3049 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3050 CurArgIdx = Ins[i].getOrigArgIndex();
3051
3052 // Get type of the original argument.
3053 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3054 /*AllowUnknown*/ true);
3055 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3056 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3057 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3058 ValVT = MVT::i8;
3059 else if (ActualMVT == MVT::i16)
3060 ValVT = MVT::i16;
3061 }
3062 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3063 bool Res =
3064 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3065 assert(!Res && "Call operand has unhandled type");
3066 (void)Res;
3067 }
3068 assert(ArgLocs.size() == Ins.size());
3069 SmallVector<SDValue, 16> ArgValues;
3070 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3071 CCValAssign &VA = ArgLocs[i];
3072
3073 if (Ins[i].Flags.isByVal()) {
3074 // Byval is used for HFAs in the PCS, but the system should work in a
3075 // non-compliant manner for larger structs.
3076 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3077 int Size = Ins[i].Flags.getByValSize();
3078 unsigned NumRegs = (Size + 7) / 8;
3079
3080 // FIXME: This works on big-endian for composite byvals, which are the common
3081 // case. It should also work for fundamental types too.
3082 unsigned FrameIdx =
3083 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3084 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3085 InVals.push_back(FrameIdxN);
3086
3087 continue;
3088 }
3089
3090 if (VA.isRegLoc()) {
3091 // Arguments stored in registers.
3092 EVT RegVT = VA.getLocVT();
3093
3094 SDValue ArgValue;
3095 const TargetRegisterClass *RC;
3096
3097 if (RegVT == MVT::i32)
3098 RC = &AArch64::GPR32RegClass;
3099 else if (RegVT == MVT::i64)
3100 RC = &AArch64::GPR64RegClass;
3101 else if (RegVT == MVT::f16)
3102 RC = &AArch64::FPR16RegClass;
3103 else if (RegVT == MVT::f32)
3104 RC = &AArch64::FPR32RegClass;
3105 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3106 RC = &AArch64::FPR64RegClass;
3107 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3108 RC = &AArch64::FPR128RegClass;
3109 else
3110 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3111
3112 // Transform the arguments in physical registers into virtual ones.
3113 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3114 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3115
3116 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3117 // to 64 bits. Insert an assert[sz]ext to capture this, then
3118 // truncate to the right size.
3119 switch (VA.getLocInfo()) {
3120 default:
3121 llvm_unreachable("Unknown loc info!");
3122 case CCValAssign::Full:
3123 break;
3124 case CCValAssign::BCvt:
3125 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3126 break;
3127 case CCValAssign::AExt:
3128 case CCValAssign::SExt:
3129 case CCValAssign::ZExt:
3130 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3131 // nodes after our lowering.
3132 assert(RegVT == Ins[i].VT && "incorrect register location selected");
3133 break;
3134 }
3135
3136 InVals.push_back(ArgValue);
3137
3138 } else { // VA.isRegLoc()
3139 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3140 unsigned ArgOffset = VA.getLocMemOffset();
3141 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3142
3143 uint32_t BEAlign = 0;
3144 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3145 !Ins[i].Flags.isInConsecutiveRegs())
3146 BEAlign = 8 - ArgSize;
3147
3148 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3149
3150 // Create load nodes to retrieve arguments from the stack.
3151 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3152 SDValue ArgValue;
3153
3154 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3155 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3156 MVT MemVT = VA.getValVT();
3157
3158 switch (VA.getLocInfo()) {
3159 default:
3160 break;
3161 case CCValAssign::BCvt:
3162 MemVT = VA.getLocVT();
3163 break;
3164 case CCValAssign::SExt:
3165 ExtType = ISD::SEXTLOAD;
3166 break;
3167 case CCValAssign::ZExt:
3168 ExtType = ISD::ZEXTLOAD;
3169 break;
3170 case CCValAssign::AExt:
3171 ExtType = ISD::EXTLOAD;
3172 break;
3173 }
3174
3175 ArgValue = DAG.getExtLoad(
3176 ExtType, DL, VA.getLocVT(), Chain, FIN,
3177 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3178 MemVT);
3179
3180 InVals.push_back(ArgValue);
3181 }
3182 }
3183
3184 // varargs
3185 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3186 if (isVarArg) {
3187 if (!Subtarget->isTargetDarwin() || IsWin64) {
3188 // The AAPCS variadic function ABI is identical to the non-variadic
3189 // one. As a result there may be more arguments in registers and we should
3190 // save them for future reference.
3191 // Win64 variadic functions also pass arguments in registers, but all float
3192 // arguments are passed in integer registers.
3193 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3194 }
3195
3196 // This will point to the next argument passed via stack.
3197 unsigned StackOffset = CCInfo.getNextStackOffset();
3198 // We currently pass all varargs at 8-byte alignment.
3199 StackOffset = ((StackOffset + 7) & ~7);
3200 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3201
3202 if (MFI.hasMustTailInVarArgFunc()) {
3203 SmallVector<MVT, 2> RegParmTypes;
3204 RegParmTypes.push_back(MVT::i64);
3205 RegParmTypes.push_back(MVT::f128);
3206 // Compute the set of forwarded registers. The rest are scratch.
3207 SmallVectorImpl<ForwardedRegister> &Forwards =
3208 FuncInfo->getForwardedMustTailRegParms();
3209 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3210 CC_AArch64_AAPCS);
3211
3212 // Conservatively forward X8, since it might be used for aggregate return.
3213 if (!CCInfo.isAllocated(AArch64::X8)) {
3214 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3215 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3216 }
3217 }
3218 }
3219
3220 // On Windows, InReg pointers must be returned, so record the pointer in a
3221 // virtual register at the start of the function so it can be returned in the
3222 // epilogue.
3223 if (IsWin64) {
3224 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3225 if (Ins[I].Flags.isInReg()) {
3226 assert(!FuncInfo->getSRetReturnReg());
3227
3228 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3229 unsigned Reg =
3230 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3231 FuncInfo->setSRetReturnReg(Reg);
3232
3233 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3234 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3235 break;
3236 }
3237 }
3238 }
3239
3240 unsigned StackArgSize = CCInfo.getNextStackOffset();
3241 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3242 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3243 // This is a non-standard ABI so by fiat I say we're allowed to make full
3244 // use of the stack area to be popped, which must be aligned to 16 bytes in
3245 // any case:
3246 StackArgSize = alignTo(StackArgSize, 16);
3247
3248 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3249 // a multiple of 16.
3250 FuncInfo->setArgumentStackToRestore(StackArgSize);
3251
3252 // This realignment carries over to the available bytes below. Our own
3253 // callers will guarantee the space is free by giving an aligned value to
3254 // CALLSEQ_START.
3255 }
3256 // Even if we're not expected to free up the space, it's useful to know how
3257 // much is there while considering tail calls (because we can reuse it).
3258 FuncInfo->setBytesInStackArgArea(StackArgSize);
3259
3260 if (Subtarget->hasCustomCallingConv())
3261 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3262
3263 return Chain;
3264}
3265
3266void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3267 SelectionDAG &DAG,
3268 const SDLoc &DL,
3269 SDValue &Chain) const {
3270 MachineFunction &MF = DAG.getMachineFunction();
3271 MachineFrameInfo &MFI = MF.getFrameInfo();
3272 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3273 auto PtrVT = getPointerTy(DAG.getDataLayout());
3274 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3275
3276 SmallVector<SDValue, 8> MemOps;
3277
3278 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3279 AArch64::X3, AArch64::X4, AArch64::X5,
3280 AArch64::X6, AArch64::X7 };
3281 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3282 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3283
3284 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3285 int GPRIdx = 0;
3286 if (GPRSaveSize != 0) {
3287 if (IsWin64) {
3288 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3289 if (GPRSaveSize & 15)
3290 // The extra size here, if triggered, will always be 8.
3291 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3292 } else
3293 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3294
3295 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3296
3297 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3298 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3299 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3300 SDValue Store = DAG.getStore(
3301 Val.getValue(1), DL, Val, FIN,
3302 IsWin64
3303 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3304 GPRIdx,
3305 (i - FirstVariadicGPR) * 8)
3306 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3307 MemOps.push_back(Store);
3308 FIN =
3309 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3310 }
3311 }
3312 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3313 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3314
3315 if (Subtarget->hasFPARMv8() && !IsWin64) {
3316 static const MCPhysReg FPRArgRegs[] = {
3317 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3318 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3319 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3320 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3321
3322 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3323 int FPRIdx = 0;
3324 if (FPRSaveSize != 0) {
3325 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3326
3327 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3328
3329 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3330 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3331 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3332
3333 SDValue Store = DAG.getStore(
3334 Val.getValue(1), DL, Val, FIN,
3335 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3336 MemOps.push_back(Store);
3337 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3338 DAG.getConstant(16, DL, PtrVT));
3339 }
3340 }
3341 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3342 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3343 }
3344
3345 if (!MemOps.empty()) {
3346 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3347 }
3348}
3349
3350/// LowerCallResult - Lower the result values of a call into the
3351/// appropriate copies out of appropriate physical registers.
3352SDValue AArch64TargetLowering::LowerCallResult(
3353 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3354 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3355 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3356 SDValue ThisVal) const {
3357 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3358 ? RetCC_AArch64_WebKit_JS
3359 : RetCC_AArch64_AAPCS;
3360 // Assign locations to each value returned by this call.
3361 SmallVector<CCValAssign, 16> RVLocs;
3362 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3363 *DAG.getContext());
3364 CCInfo.AnalyzeCallResult(Ins, RetCC);
3365
3366 // Copy all of the result registers out of their specified physreg.
3367 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3368 CCValAssign VA = RVLocs[i];
3369
3370 // Pass 'this' value directly from the argument to return value, to avoid
3371 // reg unit interference
3372 if (i == 0 && isThisReturn) {
3373 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3374 "unexpected return calling convention register assignment");
3375 InVals.push_back(ThisVal);
3376 continue;
3377 }
3378
3379 SDValue Val =
3380 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3381 Chain = Val.getValue(1);
3382 InFlag = Val.getValue(2);
3383
3384 switch (VA.getLocInfo()) {
3385 default:
3386 llvm_unreachable("Unknown loc info!");
3387 case CCValAssign::Full:
3388 break;
3389 case CCValAssign::BCvt:
3390 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3391 break;
3392 }
3393
3394 InVals.push_back(Val);
3395 }
3396
3397 return Chain;
3398}
3399
3400/// Return true if the calling convention is one that we can guarantee TCO for.
3401static bool canGuaranteeTCO(CallingConv::ID CC) {
3402 return CC == CallingConv::Fast;
3403}
3404
3405/// Return true if we might ever do TCO for calls with this calling convention.
3406static bool mayTailCallThisCC(CallingConv::ID CC) {
3407 switch (CC) {
3408 case CallingConv::C:
3409 case CallingConv::PreserveMost:
3410 case CallingConv::Swift:
3411 return true;
3412 default:
3413 return canGuaranteeTCO(CC);
3414 }
3415}
3416
3417bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3418 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3419 const SmallVectorImpl<ISD::OutputArg> &Outs,
3420 const SmallVectorImpl<SDValue> &OutVals,
3421 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3422 if (!mayTailCallThisCC(CalleeCC))
3423 return false;
3424
3425 MachineFunction &MF = DAG.getMachineFunction();
3426 const Function &CallerF = MF.getFunction();
3427 CallingConv::ID CallerCC = CallerF.getCallingConv();
3428 bool CCMatch = CallerCC == CalleeCC;
3429
3430 // Byval parameters hand the function a pointer directly into the stack area
3431 // we want to reuse during a tail call. Working around this *is* possible (see
3432 // X86) but less efficient and uglier in LowerCall.
3433 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3434 e = CallerF.arg_end();
3435 i != e; ++i) {
3436 if (i->hasByValAttr())
3437 return false;
3438
3439 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3440 // In this case, it is necessary to save/restore X0 in the callee. Tail
3441 // call opt interferes with this. So we disable tail call opt when the
3442 // caller has an argument with "inreg" attribute.
3443
3444 // FIXME: Check whether the callee also has an "inreg" argument.
3445 if (i->hasInRegAttr())
3446 return false;
3447 }
3448
3449 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3450 return canGuaranteeTCO(CalleeCC) && CCMatch;
3451
3452 // Externally-defined functions with weak linkage should not be
3453 // tail-called on AArch64 when the OS does not support dynamic
3454 // pre-emption of symbols, as the AAELF spec requires normal calls
3455 // to undefined weak functions to be replaced with a NOP or jump to the
3456 // next instruction. The behaviour of branch instructions in this
3457 // situation (as used for tail calls) is implementation-defined, so we
3458 // cannot rely on the linker replacing the tail call with a return.
3459 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3460 const GlobalValue *GV = G->getGlobal();
3461 const Triple &TT = getTargetMachine().getTargetTriple();
3462 if (GV->hasExternalWeakLinkage() &&
3463 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3464 return false;
3465 }
3466
3467 // Now we search for cases where we can use a tail call without changing the
3468 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3469 // concept.
3470
3471 // I want anyone implementing a new calling convention to think long and hard
3472 // about this assert.
3473 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3474 "Unexpected variadic calling convention");
3475
3476 LLVMContext &C = *DAG.getContext();
3477 if (isVarArg && !Outs.empty()) {
3478 // At least two cases here: if caller is fastcc then we can't have any
3479 // memory arguments (we'd be expected to clean up the stack afterwards). If
3480 // caller is C then we could potentially use its argument area.
3481
3482 // FIXME: for now we take the most conservative of these in both cases:
3483 // disallow all variadic memory operands.
3484 SmallVector<CCValAssign, 16> ArgLocs;
3485 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3486
3487 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3488 for (const CCValAssign &ArgLoc : ArgLocs)
3489 if (!ArgLoc.isRegLoc())
3490 return false;
3491 }
3492
3493 // Check that the call results are passed in the same way.
3494 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3495 CCAssignFnForCall(CalleeCC, isVarArg),
3496 CCAssignFnForCall(CallerCC, isVarArg)))
3497 return false;
3498 // The callee has to preserve all registers the caller needs to preserve.
3499 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3500 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3501 if (!CCMatch) {
3502 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3503 if (Subtarget->hasCustomCallingConv()) {
3504 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3505 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3506 }
3507 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3508 return false;
3509 }
3510
3511 // Nothing more to check if the callee is taking no arguments
3512 if (Outs.empty())
3513 return true;
3514
3515 SmallVector<CCValAssign, 16> ArgLocs;
3516 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3517
3518 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3519
3520 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3521
3522 // If the stack arguments for this call do not fit into our own save area then
3523 // the call cannot be made tail.
3524 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3525 return false;
3526
3527 const MachineRegisterInfo &MRI = MF.getRegInfo();
3528 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3529 return false;
3530
3531 return true;
3532}
3533
3534SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3535 SelectionDAG &DAG,
3536 MachineFrameInfo &MFI,
3537 int ClobberedFI) const {
3538 SmallVector<SDValue, 8> ArgChains;
3539 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3540 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3541
3542 // Include the original chain at the beginning of the list. When this is
3543 // used by target LowerCall hooks, this helps legalize find the
3544 // CALLSEQ_BEGIN node.
3545 ArgChains.push_back(Chain);
3546
3547 // Add a chain value for each stack argument corresponding
3548 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3549 UE = DAG.getEntryNode().getNode()->use_end();
3550 U != UE; ++U)
3551 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3552 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3553 if (FI->getIndex() < 0) {
3554 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3555 int64_t InLastByte = InFirstByte;
3556 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3557
3558 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3559 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3560 ArgChains.push_back(SDValue(L, 1));
3561 }
3562
3563 // Build a tokenfactor for all the chains.
3564 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3565}
3566
3567bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3568 bool TailCallOpt) const {
3569 return CallCC == CallingConv::Fast && TailCallOpt;
3570}
3571
3572/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3573/// and add input and output parameter nodes.
3574SDValue
3575AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3576 SmallVectorImpl<SDValue> &InVals) const {
3577 SelectionDAG &DAG = CLI.DAG;
3578 SDLoc &DL = CLI.DL;
3579 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3580 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3581 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3582 SDValue Chain = CLI.Chain;
3583 SDValue Callee = CLI.Callee;
3584 bool &IsTailCall = CLI.IsTailCall;
3585 CallingConv::ID CallConv = CLI.CallConv;
3586 bool IsVarArg = CLI.IsVarArg;
3587
3588 MachineFunction &MF = DAG.getMachineFunction();
3589 bool IsThisReturn = false;
3590
3591 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3592 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3593 bool IsSibCall = false;
3594
3595 if (IsTailCall) {
3596 // Check if it's really possible to do a tail call.
3597 IsTailCall = isEligibleForTailCallOptimization(
3598 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3599 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3600 report_fatal_error("failed to perform tail call elimination on a call "
3601 "site marked musttail");
3602
3603 // A sibling call is one where we're under the usual C ABI and not planning
3604 // to change that but can still do a tail call:
3605 if (!TailCallOpt && IsTailCall)
3606 IsSibCall = true;
3607
3608 if (IsTailCall)
3609 ++NumTailCalls;
3610 }
3611
3612 // Analyze operands of the call, assigning locations to each operand.
3613 SmallVector<CCValAssign, 16> ArgLocs;
3614 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3615 *DAG.getContext());
3616
3617 if (IsVarArg) {
3618 // Handle fixed and variable vector arguments differently.
3619 // Variable vector arguments always go into memory.
3620 unsigned NumArgs = Outs.size();
3621
3622 for (unsigned i = 0; i != NumArgs; ++i) {
3623 MVT ArgVT = Outs[i].VT;
3624 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3625 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3626 /*IsVarArg=*/ !Outs[i].IsFixed);
3627 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3628 assert(!Res && "Call operand has unhandled type");
3629 (void)Res;
3630 }
3631 } else {
3632 // At this point, Outs[].VT may already be promoted to i32. To correctly
3633 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3634 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3635 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3636 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3637 // LocVT.
3638 unsigned NumArgs = Outs.size();
3639 for (unsigned i = 0; i != NumArgs; ++i) {
3640 MVT ValVT = Outs[i].VT;
3641 // Get type of the original argument.
3642 EVT ActualVT = getValueType(DAG.getDataLayout(),
3643 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3644 /*AllowUnknown*/ true);
3645 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3646 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3647 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3648 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3649 ValVT = MVT::i8;
3650 else if (ActualMVT == MVT::i16)
3651 ValVT = MVT::i16;
3652
3653 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3654 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3655 assert(!Res && "Call operand has unhandled type");
3656 (void)Res;
3657 }
3658 }
3659
3660 // Get a count of how many bytes are to be pushed on the stack.
3661 unsigned NumBytes = CCInfo.getNextStackOffset();
3662
3663 if (IsSibCall) {
3664 // Since we're not changing the ABI to make this a tail call, the memory
3665 // operands are already available in the caller's incoming argument space.
3666 NumBytes = 0;
3667 }
3668
3669 // FPDiff is the byte offset of the call's argument area from the callee's.
3670 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3671 // by this amount for a tail call. In a sibling call it must be 0 because the
3672 // caller will deallocate the entire stack and the callee still expects its
3673 // arguments to begin at SP+0. Completely unused for non-tail calls.
3674 int FPDiff = 0;
3675
3676 if (IsTailCall && !IsSibCall) {
3677 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3678
3679 // Since callee will pop argument stack as a tail call, we must keep the
3680 // popped size 16-byte aligned.
3681 NumBytes = alignTo(NumBytes, 16);
3682
3683 // FPDiff will be negative if this tail call requires more space than we
3684 // would automatically have in our incoming argument space. Positive if we
3685 // can actually shrink the stack.
3686 FPDiff = NumReusableBytes - NumBytes;
3687
3688 // The stack pointer must be 16-byte aligned at all times it's used for a
3689 // memory operation, which in practice means at *all* times and in
3690 // particular across call boundaries. Therefore our own arguments started at
3691 // a 16-byte aligned SP and the delta applied for the tail call should
3692 // satisfy the same constraint.
3693 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3694 }
3695
3696 // Adjust the stack pointer for the new arguments...
3697 // These operations are automatically eliminated by the prolog/epilog pass
3698 if (!IsSibCall)
3699 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3700
3701 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3702 getPointerTy(DAG.getDataLayout()));
3703
3704 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3705 SmallVector<SDValue, 8> MemOpChains;
3706 auto PtrVT = getPointerTy(DAG.getDataLayout());
3707
3708 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3709 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3710 for (const auto &F : Forwards) {
3711 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3712 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3713 }
3714 }
3715
3716 // Walk the register/memloc assignments, inserting copies/loads.
3717 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3718 ++i, ++realArgIdx) {
3719 CCValAssign &VA = ArgLocs[i];
3720 SDValue Arg = OutVals[realArgIdx];
3721 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3722
3723 // Promote the value if needed.
3724 switch (VA.getLocInfo()) {
3725 default:
3726 llvm_unreachable("Unknown loc info!");
3727 case CCValAssign::Full:
3728 break;
3729 case CCValAssign::SExt:
3730 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3731 break;
3732 case CCValAssign::ZExt:
3733 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3734 break;
3735 case CCValAssign::AExt:
3736 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3737 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3738 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3739 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3740 }
3741 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3742 break;
3743 case CCValAssign::BCvt:
3744 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3745 break;
3746 case CCValAssign::FPExt:
3747 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3748 break;
3749 }
3750
3751 if (VA.isRegLoc()) {
3752 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3753 Outs[0].VT == MVT::i64) {
3754 assert(VA.getLocVT() == MVT::i64 &&
3755 "unexpected calling convention register assignment");
3756 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3757 "unexpected use of 'returned'");
3758 IsThisReturn = true;
3759 }
3760 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3761 } else {
3762 assert(VA.isMemLoc());
3763
3764 SDValue DstAddr;
3765 MachinePointerInfo DstInfo;
3766
3767 // FIXME: This works on big-endian for composite byvals, which are the
3768 // common case. It should also work for fundamental types too.
3769 uint32_t BEAlign = 0;
3770 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3771 : VA.getValVT().getSizeInBits();
3772 OpSize = (OpSize + 7) / 8;
3773 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3774 !Flags.isInConsecutiveRegs()) {
3775 if (OpSize < 8)
3776 BEAlign = 8 - OpSize;
3777 }
3778 unsigned LocMemOffset = VA.getLocMemOffset();
3779 int32_t Offset = LocMemOffset + BEAlign;
3780 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3781 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3782
3783 if (IsTailCall) {
3784 Offset = Offset + FPDiff;
3785 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3786
3787 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3788 DstInfo =
3789 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3790
3791 // Make sure any stack arguments overlapping with where we're storing
3792 // are loaded before this eventual operation. Otherwise they'll be
3793 // clobbered.
3794 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3795 } else {
3796 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3797
3798 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3799 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3800 LocMemOffset);
3801 }
3802
3803 if (Outs[i].Flags.isByVal()) {
3804 SDValue SizeNode =
3805 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3806 SDValue Cpy = DAG.getMemcpy(
3807 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3808 /*isVol = */ false, /*AlwaysInline = */ false,
3809 /*isTailCall = */ false, /*MustPreserveCheriCapabilities = */ false,
3810 DstInfo, MachinePointerInfo());
3811
3812 MemOpChains.push_back(Cpy);
3813 } else {
3814 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3815 // promoted to a legal register type i32, we should truncate Arg back to
3816 // i1/i8/i16.
3817 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3818 VA.getValVT() == MVT::i16)
3819 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3820
3821 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3822 MemOpChains.push_back(Store);
3823 }
3824 }
3825 }
3826
3827 if (!MemOpChains.empty())
3828 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3829
3830 // Build a sequence of copy-to-reg nodes chained together with token chain
3831 // and flag operands which copy the outgoing args into the appropriate regs.
3832 SDValue InFlag;
3833 for (auto &RegToPass : RegsToPass) {
3834 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3835 RegToPass.second, InFlag);
3836 InFlag = Chain.getValue(1);
3837 }
3838
3839 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3840 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3841 // node so that legalize doesn't hack it.
3842 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3843 auto GV = G->getGlobal();
3844 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3845 AArch64II::MO_GOT) {
3846 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3847 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3848 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3849 assert(Subtarget->isTargetWindows() &&
3850 "Windows is the only supported COFF target");
3851 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3852 } else {
3853 const GlobalValue *GV = G->getGlobal();
3854 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3855 }
3856 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3857 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3858 Subtarget->isTargetMachO()) {
3859 const char *Sym = S->getSymbol();
3860 Callee = DAG.getTargetExternalFunctionSymbol(Sym, AArch64II::MO_GOT);
3861 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3862 } else {
3863 const char *Sym = S->getSymbol();
3864 Callee = DAG.getTargetExternalFunctionSymbol(Sym, 0);
3865 }
3866 }
3867
3868 // We don't usually want to end the call-sequence here because we would tidy
3869 // the frame up *after* the call, however in the ABI-changing tail-call case
3870 // we've carefully laid out the parameters so that when sp is reset they'll be
3871 // in the correct location.
3872 if (IsTailCall && !IsSibCall) {
3873 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3874 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3875 InFlag = Chain.getValue(1);
3876 }
3877
3878 std::vector<SDValue> Ops;
3879 Ops.push_back(Chain);
3880 Ops.push_back(Callee);
3881
3882 if (IsTailCall) {
3883 // Each tail call may have to adjust the stack by a different amount, so
3884 // this information must travel along with the operation for eventual
3885 // consumption by emitEpilogue.
3886 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3887 }
3888
3889 // Add argument registers to the end of the list so that they are known live
3890 // into the call.
3891 for (auto &RegToPass : RegsToPass)
3892 Ops.push_back(DAG.getRegister(RegToPass.first,
3893 RegToPass.second.getValueType()));
3894
3895 // Add a register mask operand representing the call-preserved registers.
3896 const uint32_t *Mask;
3897 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3898 if (IsThisReturn) {
3899 // For 'this' returns, use the X0-preserving mask if applicable
3900 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3901 if (!Mask) {
3902 IsThisReturn = false;
3903 Mask = TRI->getCallPreservedMask(MF, CallConv);
3904 }
3905 } else
3906 Mask = TRI->getCallPreservedMask(MF, CallConv);
3907
3908 if (Subtarget->hasCustomCallingConv())
3909 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3910
3911 if (TRI->isAnyArgRegReserved(MF))
3912 TRI->emitReservedArgRegCallError(MF);
3913
3914 assert(Mask && "Missing call preserved mask for calling convention");
3915 Ops.push_back(DAG.getRegisterMask(Mask));
3916
3917 if (InFlag.getNode())
3918 Ops.push_back(InFlag);
3919
3920 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3921
3922 // If we're doing a tall call, use a TC_RETURN here rather than an
3923 // actual call instruction.
3924 if (IsTailCall) {
3925 MF.getFrameInfo().setHasTailCall();
3926 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3927 }
3928
3929 // Returns a chain and a flag for retval copy to use.
3930 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3931 InFlag = Chain.getValue(1);
3932
3933 uint64_t CalleePopBytes =
3934 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3935
3936 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3937 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3938 InFlag, DL);
3939 if (!Ins.empty())
3940 InFlag = Chain.getValue(1);
3941
3942 // Handle result values, copying them out of physregs into vregs that we
3943 // return.
3944 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3945 InVals, IsThisReturn,
3946 IsThisReturn ? OutVals[0] : SDValue());
3947}
3948
3949bool AArch64TargetLowering::CanLowerReturn(
3950 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3951 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3952 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3953 ? RetCC_AArch64_WebKit_JS
3954 : RetCC_AArch64_AAPCS;
3955 SmallVector<CCValAssign, 16> RVLocs;
3956 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3957 return CCInfo.CheckReturn(Outs, RetCC);
3958}
3959
3960SDValue
3961AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3962 bool isVarArg,
3963 const SmallVectorImpl<ISD::OutputArg> &Outs,
3964 const SmallVectorImpl<SDValue> &OutVals,
3965 const SDLoc &DL, SelectionDAG &DAG) const {
3966 auto &MF = DAG.getMachineFunction();
3967 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3968
3969 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3970 ? RetCC_AArch64_WebKit_JS
3971 : RetCC_AArch64_AAPCS;
3972 SmallVector<CCValAssign, 16> RVLocs;
3973 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3974 *DAG.getContext());
3975 CCInfo.AnalyzeReturn(Outs, RetCC);
3976
3977 // Copy the result values into the output registers.
3978 SDValue Flag;
3979 SmallVector<SDValue, 4> RetOps(1, Chain);
3980 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3981 ++i, ++realRVLocIdx) {
3982 CCValAssign &VA = RVLocs[i];
3983 assert(VA.isRegLoc() && "Can only return in registers!");
3984 SDValue Arg = OutVals[realRVLocIdx];
3985
3986 switch (VA.getLocInfo()) {
3987 default:
3988 llvm_unreachable("Unknown loc info!");
3989 case CCValAssign::Full:
3990 if (Outs[i].ArgVT == MVT::i1) {
3991 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3992 // value. This is strictly redundant on Darwin (which uses "zeroext
3993 // i1"), but will be optimised out before ISel.
3994 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3995 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3996 }
3997 break;
3998 case CCValAssign::BCvt:
3999 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4000 break;
4001 }
4002
4003 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4004 Flag = Chain.getValue(1);
4005 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4006 }
4007
4008 // Windows AArch64 ABIs require that for returning structs by value we copy
4009 // the sret argument into X0 for the return.
4010 // We saved the argument into a virtual register in the entry block,
4011 // so now we copy the value out and into X0.
4012 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4013 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4014 getPointerTy(MF.getDataLayout()));
4015
4016 unsigned RetValReg = AArch64::X0;
4017 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4018 Flag = Chain.getValue(1);
4019
4020 RetOps.push_back(
4021 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4022 }
4023
4024 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4025 const MCPhysReg *I =
4026 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4027 if (I) {
4028 for (; *I; ++I) {
4029 if (AArch64::GPR64RegClass.contains(*I))
4030 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4031 else if (AArch64::FPR64RegClass.contains(*I))
4032 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4033 else
4034 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4035 }
4036 }
4037
4038 RetOps[0] = Chain; // Update chain.
4039
4040 // Add the flag if we have it.
4041 if (Flag.getNode())
4042 RetOps.push_back(Flag);
4043
4044 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4045}
4046
4047//===----------------------------------------------------------------------===//
4048// Other Lowering Code
4049//===----------------------------------------------------------------------===//
4050
4051SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4052 SelectionDAG &DAG,
4053 unsigned Flag) const {
4054 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4055 N->getOffset(), Flag);
4056}
4057
4058SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4059 SelectionDAG &DAG,
4060 unsigned Flag) const {
4061 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4062}
4063
4064SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4065 SelectionDAG &DAG,
4066 unsigned Flag) const {
4067 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4068 N->getOffset(), Flag);
4069}
4070
4071SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4072 SelectionDAG &DAG,
4073 unsigned Flag) const {
4074 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4075}
4076
4077// (loadGOT sym)
4078template <class NodeTy>
4079SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4080 unsigned Flags) const {
4081 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4082 SDLoc DL(N);
4083 EVT Ty = getPointerTy(DAG.getDataLayout());
4084 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4085 // FIXME: Once remat is capable of dealing with instructions with register
4086 // operands, expand this into two nodes instead of using a wrapper node.
4087 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4088}
4089
4090// (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4091template <class NodeTy>
4092SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4093 unsigned Flags) const {
4094 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4095 SDLoc DL(N);
4096 EVT Ty = getPointerTy(DAG.getDataLayout());
4097 const unsigned char MO_NC = AArch64II::MO_NC;
4098 return DAG.getNode(
4099 AArch64ISD::WrapperLarge, DL, Ty,
4100 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4101 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4102 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4103 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4104}
4105
4106// (addlow (adrp %hi(sym)) %lo(sym))
4107template <class NodeTy>
4108SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4109 unsigned Flags) const {
4110 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4111 SDLoc DL(N);
4112 EVT Ty = getPointerTy(DAG.getDataLayout());
4113 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4114 SDValue Lo = getTargetNode(N, Ty, DAG,
4115 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4116 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4117 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4118}
4119
4120// (adr sym)
4121template <class NodeTy>
4122SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4123 unsigned Flags) const {
4124 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4125 SDLoc DL(N);
4126 EVT Ty = getPointerTy(DAG.getDataLayout());
4127 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4128 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4129}
4130
4131SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4132 SelectionDAG &DAG) const {
4133 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4134 const GlobalValue *GV = GN->getGlobal();
4135 unsigned char OpFlags =
4136 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4137
4138 if (OpFlags != AArch64II::MO_NO_FLAG)
4139 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4140 "unexpected offset in global node");
4141
4142 // This also catches the large code model case for Darwin, and tiny code
4143 // model with got relocations.
4144 if ((OpFlags & AArch64II::MO_GOT) != 0) {
4145 return getGOT(GN, DAG, OpFlags);
4146 }
4147
4148 SDValue Result;
4149 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4150 Result = getAddrLarge(GN, DAG, OpFlags);
4151 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4152 Result = getAddrTiny(GN, DAG, OpFlags);
4153 } else {
4154 Result = getAddr(GN, DAG, OpFlags);
4155 }
4156 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4157 SDLoc DL(GN);
4158 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4159 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4160 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4161 return Result;
4162}
4163
4164/// Convert a TLS address reference into the correct sequence of loads
4165/// and calls to compute the variable's address (for Darwin, currently) and
4166/// return an SDValue containing the final node.
4167
4168/// Darwin only has one TLS scheme which must be capable of dealing with the
4169/// fully general situation, in the worst case. This means:
4170/// + "extern __thread" declaration.
4171/// + Defined in a possibly unknown dynamic library.
4172///
4173/// The general system is that each __thread variable has a [3 x i64] descriptor
4174/// which contains information used by the runtime to calculate the address. The
4175/// only part of this the compiler needs to know about is the first xword, which
4176/// contains a function pointer that must be called with the address of the
4177/// entire descriptor in "x0".
4178///
4179/// Since this descriptor may be in a different unit, in general even the
4180/// descriptor must be accessed via an indirect load. The "ideal" code sequence
4181/// is:
4182/// adrp x0, _var@TLVPPAGE
4183/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4184/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4185/// ; the function pointer
4186/// blr x1 ; Uses descriptor address in x0
4187/// ; Address of _var is now in x0.
4188///
4189/// If the address of _var's descriptor *is* known to the linker, then it can
4190/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4191/// a slight efficiency gain.
4192SDValue
4193AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4194 SelectionDAG &DAG) const {
4195 assert(Subtarget->isTargetDarwin() &&
4196 "This function expects a Darwin target");
4197
4198 SDLoc DL(Op);
4199 MVT PtrVT = getPointerTy(DAG.getDataLayout());
4200 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4201
4202 SDValue TLVPAddr =
4203 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4204 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4205
4206 // The first entry in the descriptor is a function pointer that we must call
4207 // to obtain the address of the variable.
4208 SDValue Chain = DAG.getEntryNode();
4209 SDValue FuncTLVGet = DAG.getLoad(
4210 MVT::i64, DL, Chain, DescAddr,
4211 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4212 /* Alignment = */ 8,
4213 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
4214 MachineMemOperand::MODereferenceable);
4215 Chain = FuncTLVGet.getValue(1);
4216
4217 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4218 MFI.setAdjustsStack(true);
4219
4220 // TLS calls preserve all registers except those that absolutely must be
4221 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4222 // silly).
4223 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4224 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4225 if (Subtarget->hasCustomCallingConv())
4226 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4227
4228 // Finally, we can make the call. This is just a degenerate version of a
4229 // normal AArch64 call node: x0 takes the address of the descriptor, and
4230 // returns the address of the variable in this thread.
4231 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4232 Chain =
4233 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4234 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4235 DAG.getRegisterMask(Mask), Chain.getValue(1));
4236 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4237}
4238
4239/// When accessing thread-local variables under either the general-dynamic or
4240/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4241/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4242/// is a function pointer to carry out the resolution.
4243///
4244/// The sequence is:
4245/// adrp x0, :tlsdesc:var
4246/// ldr x1, [x0, #:tlsdesc_lo12:var]
4247/// add x0, x0, #:tlsdesc_lo12:var
4248/// .tlsdesccall var
4249/// blr x1
4250/// (TPIDR_EL0 offset now in x0)
4251///
4252/// The above sequence must be produced unscheduled, to enable the linker to
4253/// optimize/relax this sequence.
4254/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4255/// above sequence, and expanded really late in the compilation flow, to ensure
4256/// the sequence is produced as per above.
4257SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4258 const SDLoc &DL,
4259 SelectionDAG &DAG) const {
4260 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4261
4262 SDValue Chain = DAG.getEntryNode();
4263 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4264
4265 Chain =
4266 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4267 SDValue Glue = Chain.getValue(1);
4268
4269 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4270}
4271
4272SDValue
4273AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4274 SelectionDAG &DAG) const {
4275 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4276 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4277 report_fatal_error("ELF TLS only supported in small memory model");
4278 // Different choices can be made for the maximum size of the TLS area for a
4279 // module. For the small address model, the default TLS size is 16MiB and the
4280 // maximum TLS size is 4GiB.
4281 // FIXME: add -mtls-size command line option and make it control the 16MiB
4282 // vs. 4GiB code sequence generation.
4283 // FIXME: add tiny codemodel support. We currently generate the same code as
4284 // small, which may be larger than needed.
4285 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4286
4287 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4288
4289 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4290 if (Model == TLSModel::LocalDynamic)
4291 Model = TLSModel::GeneralDynamic;
4292 }
4293
4294 SDValue TPOff;
4295 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4296 SDLoc DL(Op);
4297 const GlobalValue *GV = GA->getGlobal();
4298
4299 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4300
4301 if (Model == TLSModel::LocalExec) {
4302 SDValue HiVar = DAG.getTargetGlobalAddress(
4303 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4304 SDValue LoVar = DAG.getTargetGlobalAddress(
4305 GV, DL, PtrVT, 0,
4306 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4307
4308 SDValue TPWithOff_lo =
4309 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4310 HiVar,
4311 DAG.getTargetConstant(0, DL, MVT::i32)),
4312 0);
4313 SDValue TPWithOff =
4314 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4315 LoVar,
4316 DAG.getTargetConstant(0, DL, MVT::i32)),
4317 0);
4318 return TPWithOff;
4319 } else if (Model == TLSModel::InitialExec) {
4320 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4321 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4322 } else if (Model == TLSModel::LocalDynamic) {
4323 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4324 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4325 // the beginning of the module's TLS region, followed by a DTPREL offset
4326 // calculation.
4327
4328 // These accesses will need deduplicating if there's more than one.
4329 AArch64FunctionInfo *MFI =
4330 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4331 MFI->incNumLocalDynamicTLSAccesses();
4332
4333 // The call needs a relocation too for linker relaxation. It doesn't make
4334 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4335 // the address.
4336 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4337 AArch64II::MO_TLS);
4338
4339 // Now we can calculate the offset from TPIDR_EL0 to this module's
4340 // thread-local area.
4341 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4342
4343 // Now use :dtprel_whatever: operations to calculate this variable's offset
4344 // in its thread-storage area.
4345 SDValue HiVar = DAG.getTargetGlobalAddress(
4346 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4347 SDValue LoVar = DAG.getTargetGlobalAddress(
4348 GV, DL, MVT::i64, 0,
4349 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4350
4351 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4352 DAG.getTargetConstant(0, DL, MVT::i32)),
4353 0);
4354 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4355 DAG.getTargetConstant(0, DL, MVT::i32)),
4356 0);
4357 } else if (Model == TLSModel::GeneralDynamic) {
4358 // The call needs a relocation too for linker relaxation. It doesn't make
4359 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4360 // the address.
4361 SDValue SymAddr =
4362 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4363
4364 // Finally we can make a call to calculate the offset from tpidr_el0.
4365 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4366 } else
4367 llvm_unreachable("Unsupported ELF TLS access model");
4368
4369 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4370}
4371
4372SDValue
4373AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4374 SelectionDAG &DAG) const {
4375 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4376
4377 SDValue Chain = DAG.getEntryNode();
4378 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4379 SDLoc DL(Op);
4380
4381 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4382
4383 // Load the ThreadLocalStoragePointer from the TEB
4384 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4385 SDValue TLSArray =
4386 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4387 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4388 Chain = TLSArray.getValue(1);
4389
4390 // Load the TLS index from the C runtime;
4391 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4392 // This also does the same as LOADgot, but using a generic i32 load,
4393 // while LOADgot only loads i64.
4394 SDValue TLSIndexHi =
4395 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4396 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4397 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4398 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4399 SDValue TLSIndex =
4400 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4401 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4402 Chain = TLSIndex.getValue(1);
4403
4404 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4405 // offset into the TLSArray.
4406 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4407 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4408 DAG.getConstant(3, DL, PtrVT));
4409 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4410 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4411 MachinePointerInfo());
4412 Chain = TLS.getValue(1);
4413
4414 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4415 const GlobalValue *GV = GA->getGlobal();
4416 SDValue TGAHi = DAG.getTargetGlobalAddress(
4417 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4418 SDValue TGALo = DAG.getTargetGlobalAddress(
4419 GV, DL, PtrVT, 0,
4420 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4421
4422 // Add the offset from the start of the .tls section (section base).
4423 SDValue Addr =
4424 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4425 DAG.getTargetConstant(0, DL, MVT::i32)),
4426 0);
4427 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4428 return Addr;
4429}
4430
4431SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4432 SelectionDAG &DAG) const {
4433 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4434 if (DAG.getTarget().useEmulatedTLS())
4435 return LowerToTLSEmulatedModel(GA, DAG);
4436
4437 if (Subtarget->isTargetDarwin())
4438 return LowerDarwinGlobalTLSAddress(Op, DAG);
4439 if (Subtarget->isTargetELF())
4440 return LowerELFGlobalTLSAddress(Op, DAG);
4441 if (Subtarget->isTargetWindows())
4442 return LowerWindowsGlobalTLSAddress(Op, DAG);
4443
4444 llvm_unreachable("Unexpected platform trying to use TLS");
4445}
4446
4447SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4448 SDValue Chain = Op.getOperand(0);
4449 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4450 SDValue LHS = Op.getOperand(2);
4451 SDValue RHS = Op.getOperand(3);
4452 SDValue Dest = Op.getOperand(4);
4453 SDLoc dl(Op);
4454
4455 MachineFunction &MF = DAG.getMachineFunction();
4456 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4457 // will not be produced, as they are conditional branch instructions that do
4458 // not set flags.
4459 bool ProduceNonFlagSettingCondBr =
4460 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4461
4462 // Handle f128 first, since lowering it will result in comparing the return
4463 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4464 // is expecting to deal with.
4465 if (LHS.getValueType() == MVT::f128) {
4466 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4467
4468 // If softenSetCCOperands returned a scalar, we need to compare the result
4469 // against zero to select between true and false values.
4470 if (!RHS.getNode()) {
4471 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4472 CC = ISD::SETNE;
4473 }
4474 }
4475
4476 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4477 // instruction.
4478 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4479 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4480 // Only lower legal XALUO ops.
4481 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4482 return SDValue();
4483
4484 // The actual operation with overflow check.
4485 AArch64CC::CondCode OFCC;
4486 SDValue Value, Overflow;
4487 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4488
4489 if (CC == ISD::SETNE)
4490 OFCC = getInvertedCondCode(OFCC);
4491 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4492
4493 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4494 Overflow);
4495 }
4496
4497 if (LHS.getValueType().isInteger()) {
4498 assert((LHS.getValueType() == RHS.getValueType()) &&
4499 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4500
4501 // If the RHS of the comparison is zero, we can potentially fold this
4502 // to a specialized branch.
4503 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4504 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4505 if (CC == ISD::SETEQ) {
4506 // See if we can use a TBZ to fold in an AND as well.
4507 // TBZ has a smaller branch displacement than CBZ. If the offset is
4508 // out of bounds, a late MI-layer pass rewrites branches.
4509 // 403.gcc is an example that hits this case.
4510 if (LHS.getOpcode() == ISD::AND &&
4511 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4512 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4513 SDValue Test = LHS.getOperand(0);
4514 uint64_t Mask = LHS.getConstantOperandVal(1);
4515 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4516 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4517 Dest);
4518 }
4519
4520 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4521 } else if (CC == ISD::SETNE) {
4522 // See if we can use a TBZ to fold in an AND as well.
4523 // TBZ has a smaller branch displacement than CBZ. If the offset is
4524 // out of bounds, a late MI-layer pass rewrites branches.
4525 // 403.gcc is an example that hits this case.
4526 if (LHS.getOpcode() == ISD::AND &&
4527 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4528 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4529 SDValue Test = LHS.getOperand(0);
4530 uint64_t Mask = LHS.getConstantOperandVal(1);
4531 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4532 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4533 Dest);
4534 }
4535
4536 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4537 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4538 // Don't combine AND since emitComparison converts the AND to an ANDS
4539 // (a.k.a. TST) and the test in the test bit and branch instruction
4540 // becomes redundant. This would also increase register pressure.
4541 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4542 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4543 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4544 }
4545 }
4546 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4547 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4548 // Don't combine AND since emitComparison converts the AND to an ANDS
4549 // (a.k.a. TST) and the test in the test bit and branch instruction
4550 // becomes redundant. This would also increase register pressure.
4551 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4552 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4553 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4554 }
4555
4556 SDValue CCVal;
4557 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4558 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4559 Cmp);
4560 }
4561
4562 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4563 LHS.getValueType() == MVT::f64);
4564
4565 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4566 // clean. Some of them require two branches to implement.
4567 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4568 AArch64CC::CondCode CC1, CC2;
4569 changeFPCCToAArch64CC(CC, CC1, CC2);
4570 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4571 SDValue BR1 =
4572 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4573 if (CC2 != AArch64CC::AL) {
4574 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4575 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4576 Cmp);
4577 }
4578
4579 return BR1;
4580}
4581
4582SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4583 SelectionDAG &DAG) const {
4584 EVT VT = Op.getValueType();
4585 SDLoc DL(Op);
4586
4587 SDValue In1 = Op.getOperand(0);
4588 SDValue In2 = Op.getOperand(1);
4589 EVT SrcVT = In2.getValueType();
4590
4591 if (SrcVT.bitsLT(VT))
4592 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4593 else if (SrcVT.bitsGT(VT))
4594 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4595
4596 EVT VecVT;
4597 uint64_t EltMask;
4598 SDValue VecVal1, VecVal2;
4599
4600 auto setVecVal = [&] (int Idx) {
4601 if (!VT.isVector()) {
4602 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4603 DAG.getUNDEF(VecVT), In1);
4604 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4605 DAG.getUNDEF(VecVT), In2);
4606 } else {
4607 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4608 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4609 }
4610 };
4611
4612 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4613 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4614 EltMask = 0x80000000ULL;
4615 setVecVal(AArch64::ssub);
4616 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4617 VecVT = MVT::v2i64;
4618
4619 // We want to materialize a mask with the high bit set, but the AdvSIMD
4620 // immediate moves cannot materialize that in a single instruction for
4621 // 64-bit elements. Instead, materialize zero and then negate it.
4622 EltMask = 0;
4623
4624 setVecVal(AArch64::dsub);
4625 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4626 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4627 EltMask = 0x8000ULL;
4628 setVecVal(AArch64::hsub);
4629 } else {
4630 llvm_unreachable("Invalid type for copysign!");
4631 }
4632
4633 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4634
4635 // If we couldn't materialize the mask above, then the mask vector will be
4636 // the zero vector, and we need to negate it here.
4637 if (VT == MVT::f64 || VT == MVT::v2f64) {
4638 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4639 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4640 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4641 }
4642
4643 SDValue Sel =
4644 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4645
4646 if (VT == MVT::f16)
4647 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4648 if (VT == MVT::f32)
4649 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4650 else if (VT == MVT::f64)
4651 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4652 else
4653 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4654}
4655
4656SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4657 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4658 Attribute::NoImplicitFloat))
4659 return SDValue();
4660
4661 if (!Subtarget->hasNEON())
4662 return SDValue();
4663
4664 // While there is no integer popcount instruction, it can
4665 // be more efficiently lowered to the following sequence that uses
4666 // AdvSIMD registers/instructions as long as the copies to/from
4667 // the AdvSIMD registers are cheap.
4668 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4669 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4670 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4671 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4672 SDValue Val = Op.getOperand(0);
4673 SDLoc DL(Op);
4674 EVT VT = Op.getValueType();
4675
4676 if (VT == MVT::i32 || VT == MVT::i64) {
4677 if (VT == MVT::i32)
4678 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4679 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4680
4681 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4682 SDValue UaddLV = DAG.getNode(
4683 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4684 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4685
4686 if (VT == MVT::i64)
4687 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4688 return UaddLV;
4689 }
4690
4691 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4692 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4693 "Unexpected type for custom ctpop lowering");
4694
4695 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4696 Val = DAG.getBitcast(VT8Bit, Val);
4697 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4698
4699 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4700 unsigned EltSize = 8;
4701 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4702 while (EltSize != VT.getScalarSizeInBits()) {
4703 EltSize *= 2;
4704 NumElts /= 2;
4705 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4706 Val = DAG.getNode(
4707 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4708 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4709 }
4710
4711 return Val;
4712}
4713
4714SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4715
4716 if (Op.getValueType().isVector())
4717 return LowerVSETCC(Op, DAG);
4718
4719 SDValue LHS = Op.getOperand(0);
4720 SDValue RHS = Op.getOperand(1);
4721 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4722 SDLoc dl(Op);
4723
4724 // We chose ZeroOrOneBooleanContents, so use zero and one.
4725 EVT VT = Op.getValueType();
4726 SDValue TVal = DAG.getConstant(1, dl, VT);
4727 SDValue FVal = DAG.getConstant(0, dl, VT);
4728
4729 // Handle f128 first, since one possible outcome is a normal integer
4730 // comparison which gets picked up by the next if statement.
4731 if (LHS.getValueType() == MVT::f128) {
4732 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4733
4734 // If softenSetCCOperands returned a scalar, use it.
4735 if (!RHS.getNode()) {
4736 assert(LHS.getValueType() == Op.getValueType() &&
4737 "Unexpected setcc expansion!");
4738 return LHS;
4739 }
4740 }
4741
4742 if (LHS.getValueType().isInteger()) {
4743 SDValue CCVal;
4744 SDValue Cmp =
4745 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()),
4746 CCVal, DAG, dl);
4747
4748 // Note that we inverted the condition above, so we reverse the order of
4749 // the true and false operands here. This will allow the setcc to be
4750 // matched to a single CSINC instruction.
4751 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4752 }
4753
4754 // Now we know we're dealing with FP values.
4755 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4756 LHS.getValueType() == MVT::f64);
4757
4758 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4759 // and do the comparison.
4760 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4761
4762 AArch64CC::CondCode CC1, CC2;
4763 changeFPCCToAArch64CC(CC, CC1, CC2);
4764 if (CC2 == AArch64CC::AL) {
4765 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
4766 CC2);
4767 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4768
4769 // Note that we inverted the condition above, so we reverse the order of
4770 // the true and false operands here. This will allow the setcc to be
4771 // matched to a single CSINC instruction.
4772 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4773 } else {
4774 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4775 // totally clean. Some of them require two CSELs to implement. As is in
4776 // this case, we emit the first CSEL and then emit a second using the output
4777 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4778
4779 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4780 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4781 SDValue CS1 =
4782 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4783
4784 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4785 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4786 }
4787}
4788
4789SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4790 SDValue RHS, SDValue TVal,
4791 SDValue FVal, const SDLoc &dl,
4792 SelectionDAG &DAG) const {
4793 // Handle f128 first, because it will result in a comparison of some RTLIB
4794 // call result against zero.
4795 if (LHS.getValueType() == MVT::f128) {
4796 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4797
4798 // If softenSetCCOperands returned a scalar, we need to compare the result
4799 // against zero to select between true and false values.
4800 if (!RHS.getNode()) {
4801 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4802 CC = ISD::SETNE;
4803 }
4804 }
4805
4806 // Also handle f16, for which we need to do a f32 comparison.
4807 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4808 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4809 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4810 }
4811
4812 // Next, handle integers.
4813 if (LHS.getValueType().isInteger()) {
4814 assert((LHS.getValueType() == RHS.getValueType()) &&
4815 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4816
4817 unsigned Opcode = AArch64ISD::CSEL;
4818 EVT LHSVT = LHS.getValueType();
4819
4820 // If both the TVal and the FVal are constants, see if we can swap them in
4821 // order to for a CSINV or CSINC out of them.
4822 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4823 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4824
4825 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4826 std::swap(TVal, FVal);
4827 std::swap(CTVal, CFVal);
4828 CC = ISD::getSetCCInverse(CC, LHSVT);
4829 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4830 std::swap(TVal, FVal);
4831 std::swap(CTVal, CFVal);
4832 CC = ISD::getSetCCInverse(CC, LHSVT);
4833 } else if (TVal.getOpcode() == ISD::XOR) {
4834 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4835 // with a CSINV rather than a CSEL.
4836 if (isAllOnesConstant(TVal.getOperand(1))) {
4837 std::swap(TVal, FVal);
4838 std::swap(CTVal, CFVal);
4839 CC = ISD::getSetCCInverse(CC, LHSVT);
4840 }
4841 } else if (TVal.getOpcode() == ISD::SUB) {
4842 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4843 // that we can match with a CSNEG rather than a CSEL.
4844 if (isNullConstant(TVal.getOperand(0))) {
4845 std::swap(TVal, FVal);
4846 std::swap(CTVal, CFVal);
4847 CC = ISD::getSetCCInverse(CC, LHSVT);
4848 }
4849 } else if (CTVal && CFVal) {
4850 const int64_t TrueVal = CTVal->getSExtValue();
4851 const int64_t FalseVal = CFVal->getSExtValue();
4852 bool Swap = false;
4853
4854 // If both TVal and FVal are constants, see if FVal is the
4855 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4856 // instead of a CSEL in that case.
4857 if (TrueVal == ~FalseVal) {
4858 Opcode = AArch64ISD::CSINV;
4859 } else if (TrueVal == -FalseVal) {
4860 Opcode = AArch64ISD::CSNEG;
4861 } else if (TVal.getValueType() == MVT::i32) {
4862 // If our operands are only 32-bit wide, make sure we use 32-bit
4863 // arithmetic for the check whether we can use CSINC. This ensures that
4864 // the addition in the check will wrap around properly in case there is
4865 // an overflow (which would not be the case if we do the check with
4866 // 64-bit arithmetic).
4867 const uint32_t TrueVal32 = CTVal->getZExtValue();
4868 const uint32_t FalseVal32 = CFVal->getZExtValue();
4869
4870 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4871 Opcode = AArch64ISD::CSINC;
4872
4873 if (TrueVal32 > FalseVal32) {
4874 Swap = true;
4875 }
4876 }
4877 // 64-bit check whether we can use CSINC.
4878 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4879 Opcode = AArch64ISD::CSINC;
4880
4881 if (TrueVal > FalseVal) {
4882 Swap = true;
4883 }
4884 }
4885
4886 // Swap TVal and FVal if necessary.
4887 if (Swap) {
4888 std::swap(TVal, FVal);
4889 std::swap(CTVal, CFVal);
4890 CC = ISD::getSetCCInverse(CC, LHSVT);
4891 }
4892
4893 if (Opcode != AArch64ISD::CSEL) {
4894 // Drop FVal since we can get its value by simply inverting/negating
4895 // TVal.
4896 FVal = TVal;
4897 }
4898 }
4899
4900 // Avoid materializing a constant when possible by reusing a known value in
4901 // a register. However, don't perform this optimization if the known value
4902 // is one, zero or negative one in the case of a CSEL. We can always
4903 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4904 // FVal, respectively.
4905 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4906 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4907 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4908 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4909 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4910 // "a != C ? x : a" to avoid materializing C.
4911 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4912 TVal = LHS;
4913 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4914 FVal = LHS;
4915 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4916 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4917 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4918 // avoid materializing C.
4919 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4920 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4921 Opcode = AArch64ISD::CSINV;
4922 TVal = LHS;
4923 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4924 }
4925 }
4926
4927 SDValue CCVal;
4928 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4929 EVT VT = TVal.getValueType();
4930 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4931 }
4932
4933 // Now we know we're dealing with FP values.
4934 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4935 LHS.getValueType() == MVT::f64);
4936 assert(LHS.getValueType() == RHS.getValueType());
4937 EVT VT = TVal.getValueType();
4938 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4939
4940 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4941 // clean. Some of them require two CSELs to implement.
4942 AArch64CC::CondCode CC1, CC2;
4943 changeFPCCToAArch64CC(CC, CC1, CC2);
4944
4945 if (DAG.getTarget().Options.UnsafeFPMath) {
4946 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4947 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4948 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4949 if (RHSVal && RHSVal->isZero()) {
4950 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4951 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4952
4953 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4954 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4955 TVal = LHS;
4956 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4957 CFVal && CFVal->isZero() &&
4958 FVal.getValueType() == LHS.getValueType())
4959 FVal = LHS;
4960 }
4961 }
4962
4963 // Emit first, and possibly only, CSEL.
4964 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4965 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4966
4967 // If we need a second CSEL, emit it, using the output of the first as the
4968 // RHS. We're effectively OR'ing the two CC's together.
4969 if (CC2 != AArch64CC::AL) {
4970 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4971 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4972 }
4973
4974 // Otherwise, return the output of the first CSEL.
4975 return CS1;
4976}
4977
4978SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4979 SelectionDAG &DAG) const {
4980 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4981 SDValue LHS = Op.getOperand(0);
4982 SDValue RHS = Op.getOperand(1);
4983 SDValue TVal = Op.getOperand(2);
4984 SDValue FVal = Op.getOperand(3);
4985 SDLoc DL(Op);
4986 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4987}
4988
4989SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4990 SelectionDAG &DAG) const {
4991 SDValue CCVal = Op->getOperand(0);
4992 SDValue TVal = Op->getOperand(1);
4993 SDValue FVal = Op->getOperand(2);
4994 SDLoc DL(Op);
4995
4996 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4997 // instruction.
4998 if (isOverflowIntrOpRes(CCVal)) {
4999 // Only lower legal XALUO ops.
5000 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5001 return SDValue();
5002
5003 AArch64CC::CondCode OFCC;
5004 SDValue Value, Overflow;
5005 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5006 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5007
5008 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5009 CCVal, Overflow);
5010 }
5011
5012 // Lower it the same way as we would lower a SELECT_CC node.
5013 ISD::CondCode CC;
5014 SDValue LHS, RHS;
5015 if (CCVal.getOpcode() == ISD::SETCC) {
5016 LHS = CCVal.getOperand(0);
5017 RHS = CCVal.getOperand(1);
5018 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5019 } else {
5020 LHS = CCVal;
5021 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5022 CC = ISD::SETNE;
5023 }
5024 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5025}
5026
5027SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5028 SelectionDAG &DAG) const {
5029 // Jump table entries as PC relative offsets. No additional tweaking
5030 // is necessary here. Just get the address of the jump table.
5031 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5032
5033 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5034 !Subtarget->isTargetMachO()) {
5035 return getAddrLarge(JT, DAG);
5036 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5037 return getAddrTiny(JT, DAG);
5038 }
5039 return getAddr(JT, DAG);
5040}
5041
5042SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5043 SelectionDAG &DAG) const {
5044 // Jump table entries as PC relative offsets. No additional tweaking
5045 // is necessary here. Just get the address of the jump table.
5046 SDLoc DL(Op);
5047 SDValue JT = Op.getOperand(1);
5048 SDValue Entry = Op.getOperand(2);
5049 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5050
5051 SDNode *Dest =
5052 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5053 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5054 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5055 SDValue(Dest, 0));
5056}
5057
5058SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5059 SelectionDAG &DAG) const {
5060 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5061
5062 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5063 // Use the GOT for the large code model on iOS.
5064 if (Subtarget->isTargetMachO()) {
5065 return getGOT(CP, DAG);
5066 }
5067 return getAddrLarge(CP, DAG);
5068 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5069 return getAddrTiny(CP, DAG);
5070 } else {
5071 return getAddr(CP, DAG);
5072 }
5073}
5074
5075SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5076 SelectionDAG &DAG) const {
5077 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5078 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5079 !Subtarget->isTargetMachO()) {
5080 return getAddrLarge(BA, DAG);
5081 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5082 return getAddrTiny(BA, DAG);
5083 }
5084 return getAddr(BA, DAG);
5085}
5086
5087SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5088 SelectionDAG &DAG) const {
5089 AArch64FunctionInfo *FuncInfo =
5090 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5091
5092 SDLoc DL(Op);
5093 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5094 getPointerTy(DAG.getDataLayout()));
5095 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5096 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5097 MachinePointerInfo(SV));
5098}
5099
5100SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5101 SelectionDAG &DAG) const {
5102 AArch64FunctionInfo *FuncInfo =
5103 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5104
5105 SDLoc DL(Op);
5106 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5107 ? FuncInfo->getVarArgsGPRIndex()
5108 : FuncInfo->getVarArgsStackIndex(),
5109 getPointerTy(DAG.getDataLayout()));
5110 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5111 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5112 MachinePointerInfo(SV));
5113}
5114
5115SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5116 SelectionDAG &DAG) const {
5117 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5118 // Standard, section B.3.
5119 MachineFunction &MF = DAG.getMachineFunction();
5120 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5121 auto PtrVT = getPointerTy(DAG.getDataLayout());
5122 SDLoc DL(Op);
5123
5124 SDValue Chain = Op.getOperand(0);
5125 SDValue VAList = Op.getOperand(1);
5126 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5127 SmallVector<SDValue, 4> MemOps;
5128
5129 // void *__stack at offset 0
5130 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5131 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5132 MachinePointerInfo(SV), /* Alignment = */ 8));
5133
5134 // void *__gr_top at offset 8
5135 int GPRSize = FuncInfo->getVarArgsGPRSize();
5136 if (GPRSize > 0) {
5137 SDValue GRTop, GRTopAddr;
5138
5139 GRTopAddr =
5140 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5141
5142 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5143 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5144 DAG.getConstant(GPRSize, DL, PtrVT));
5145
5146 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5147 MachinePointerInfo(SV, 8),
5148 /* Alignment = */ 8));
5149 }
5150
5151 // void *__vr_top at offset 16
5152 int FPRSize = FuncInfo->getVarArgsFPRSize();
5153 if (FPRSize > 0) {
5154 SDValue VRTop, VRTopAddr;
5155 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5156 DAG.getConstant(16, DL, PtrVT));
5157
5158 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5159 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5160 DAG.getConstant(FPRSize, DL, PtrVT));
5161
5162 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5163 MachinePointerInfo(SV, 16),
5164 /* Alignment = */ 8));
5165 }
5166
5167 // int __gr_offs at offset 24
5168 SDValue GROffsAddr =
5169 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5170 MemOps.push_back(DAG.getStore(
5171 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5172 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5173
5174 // int __vr_offs at offset 28
5175 SDValue VROffsAddr =
5176 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5177 MemOps.push_back(DAG.getStore(
5178 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5179 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5180
5181 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5182}
5183
5184SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5185 SelectionDAG &DAG) const {
5186 MachineFunction &MF = DAG.getMachineFunction();
5187
5188 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5189 return LowerWin64_VASTART(Op, DAG);
5190 else if (Subtarget->isTargetDarwin())
5191 return LowerDarwin_VASTART(Op, DAG);
5192 else
5193 return LowerAAPCS_VASTART(Op, DAG);
5194}
5195
5196SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5197 SelectionDAG &DAG) const {
5198 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5199 // pointer.
5200 SDLoc DL(Op);
5201 unsigned VaListSize =
5202 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
5203 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5204 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5205
5206 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5207 Op.getOperand(2),
5208 DAG.getConstant(VaListSize, DL, MVT::i32),
5209 8, false, false, false, false, MachinePointerInfo(DestSV),
5210 MachinePointerInfo(SrcSV));
5211}
5212
5213SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5214 assert(Subtarget->isTargetDarwin() &&
5215 "automatic va_arg instruction only works on Darwin");
5216
5217 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5218 EVT VT = Op.getValueType();
5219 SDLoc DL(Op);
5220 SDValue Chain = Op.getOperand(0);
5221 SDValue Addr = Op.getOperand(1);
5222 unsigned Align = Op.getConstantOperandVal(3);
5223 auto PtrVT = getPointerTy(DAG.getDataLayout());
5224
5225 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
5226 Chain = VAList.getValue(1);
5227
5228 if (Align > 8) {
5229 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5230 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5231 DAG.getConstant(Align - 1, DL, PtrVT));
5232 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5233 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5234 }
5235
5236 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5237 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5238
5239 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5240 // up to 64 bits. At the very least, we have to increase the striding of the
5241 // vaargs list to match this, and for FP values we need to introduce
5242 // FP_ROUND nodes as well.
5243 if (VT.isInteger() && !VT.isVector())
5244 ArgSize = 8;
5245 bool NeedFPTrunc = false;
5246 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5247 ArgSize = 8;
5248 NeedFPTrunc = true;
5249 }
5250
5251 // Increment the pointer, VAList, to the next vaarg
5252 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5253 DAG.getConstant(ArgSize, DL, PtrVT));
5254 // Store the incremented VAList to the legalized pointer
5255 SDValue APStore =
5256 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5257
5258 // Load the actual argument out of the pointer VAList
5259 if (NeedFPTrunc) {
5260 // Load the value as an f64.
5261 SDValue WideFP =
5262 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5263 // Round the value down to an f32.
5264 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5265 DAG.getIntPtrConstant(1, DL));
5266 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5267 // Merge the rounded value with the chain output of the load.
5268 return DAG.getMergeValues(Ops, DL);
5269 }
5270
5271 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5272}
5273
5274SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5275 SelectionDAG &DAG) const {
5276 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5277 MFI.setFrameAddressIsTaken(true);
5278
5279 EVT VT = Op.getValueType();
5280 SDLoc DL(Op);
5281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5282 SDValue FrameAddr =
5283 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5284 while (Depth--)
5285 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5286 MachinePointerInfo());
5287 return FrameAddr;
5288}
5289
5290SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5291 SelectionDAG &DAG) const {
5292 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5293
5294 EVT VT = getPointerTy(DAG.getDataLayout());
5295 SDLoc DL(Op);
5296 int FI = MFI.CreateFixedObject(4, 0, false);
5297 return DAG.getFrameIndex(FI, VT);
5298}
5299
5300#define GET_REGISTER_MATCHER
5301#include "AArch64GenAsmMatcher.inc"
5302
5303// FIXME? Maybe this could be a TableGen attribute on some registers and
5304// this table could be generated automatically from RegInfo.
5305unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5306 SelectionDAG &DAG) const {
5307 unsigned Reg = MatchRegisterName(RegName);
5308 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5309 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5310 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5311 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5312 Reg = 0;
5313 }
5314 if (Reg)
5315 return Reg;
5316 report_fatal_error(Twine("Invalid register name \""
5317 + StringRef(RegName) + "\"."));
5318}
5319
5320SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5321 SelectionDAG &DAG) const {
5322 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5323
5324 EVT VT = Op.getValueType();
5325 SDLoc DL(Op);
5326
5327 SDValue FrameAddr =
5328 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5329 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5330
5331 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5332}
5333
5334SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5335 SelectionDAG &DAG) const {
5336 MachineFunction &MF = DAG.getMachineFunction();
5337 MachineFrameInfo &MFI = MF.getFrameInfo();
5338 MFI.setReturnAddressIsTaken(true);
5339
5340 EVT VT = Op.getValueType();
5341 SDLoc DL(Op);
5342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5343 if (Depth) {
5344 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5345 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5346 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5347 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5348 MachinePointerInfo());
5349 }
5350
5351 // Return LR, which contains the return address. Mark it an implicit live-in.
5352 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5353 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5354}
5355
5356/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5357/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5358SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5359 SelectionDAG &DAG) const {
5360 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5361 EVT VT = Op.getValueType();
5362 unsigned VTBits = VT.getSizeInBits();
5363 SDLoc dl(Op);
5364 SDValue ShOpLo = Op.getOperand(0);
5365 SDValue ShOpHi = Op.getOperand(1);
5366 SDValue ShAmt = Op.getOperand(2);
5367 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5368
5369 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5370
5371 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5372 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5373 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5374
5375 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5376 // is "undef". We wanted 0, so CSEL it directly.
5377 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5378 ISD::SETEQ, dl, DAG);
5379 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5380 HiBitsForLo =
5381 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5382 HiBitsForLo, CCVal, Cmp);
5383
5384 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5385 DAG.getConstant(VTBits, dl, MVT::i64));
5386
5387 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5388 SDValue LoForNormalShift =
5389 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5390
5391 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5392 dl, DAG);
5393 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5394 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5395 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5396 LoForNormalShift, CCVal, Cmp);
5397
5398 // AArch64 shifts larger than the register width are wrapped rather than
5399 // clamped, so we can't just emit "hi >> x".
5400 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5401 SDValue HiForBigShift =
5402 Opc == ISD::SRA
5403 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5404 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5405 : DAG.getConstant(0, dl, VT);
5406 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5407 HiForNormalShift, CCVal, Cmp);
5408
5409 SDValue Ops[2] = { Lo, Hi };
5410 return DAG.getMergeValues(Ops, dl);
5411}
5412
5413/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5414/// i64 values and take a 2 x i64 value to shift plus a shift amount.
5415SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5416 SelectionDAG &DAG) const {
5417 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5418 EVT VT = Op.getValueType();
5419 unsigned VTBits = VT.getSizeInBits();
5420 SDLoc dl(Op);
5421 SDValue ShOpLo = Op.getOperand(0);
5422 SDValue ShOpHi = Op.getOperand(1);
5423 SDValue ShAmt = Op.getOperand(2);
5424
5425 assert(Op.getOpcode() == ISD::SHL_PARTS);
5426 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5427 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5428 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5429
5430 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5431 // is "undef". We wanted 0, so CSEL it directly.
5432 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5433 ISD::SETEQ, dl, DAG);
5434 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5435 LoBitsForHi =
5436 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5437 LoBitsForHi, CCVal, Cmp);
5438
5439 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5440 DAG.getConstant(VTBits, dl, MVT::i64));
5441 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5442 SDValue HiForNormalShift =
5443 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5444
5445 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5446
5447 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5448 dl, DAG);
5449 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5450 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5451 HiForNormalShift, CCVal, Cmp);
5452
5453 // AArch64 shifts of larger than register sizes are wrapped rather than
5454 // clamped, so we can't just emit "lo << a" if a is too big.
5455 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5456 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5457 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5458 LoForNormalShift, CCVal, Cmp);
5459
5460 SDValue Ops[2] = { Lo, Hi };
5461 return DAG.getMergeValues(Ops, dl);
5462}
5463
5464bool AArch64TargetLowering::isOffsetFoldingLegal(
5465 const GlobalAddressSDNode *GA) const {
5466 // Offsets are folded in the DAG combine rather than here so that we can
5467 // intelligently choose an offset based on the uses.
5468 return false;
5469}
5470
5471bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5472 bool OptForSize) const {
5473 bool IsLegal = false;
5474 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5475 // 16-bit case when target has full fp16 support.
5476 // FIXME: We should be able to handle f128 as well with a clever lowering.
5477 const APInt ImmInt = Imm.bitcastToAPInt();
5478 if (VT == MVT::f64)
5479 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5480 else if (VT == MVT::f32)
5481 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5482 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5483 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5484 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5485 // generate that fmov.
5486
5487 // If we can not materialize in immediate field for fmov, check if the
5488 // value can be encoded as the immediate operand of a logical instruction.
5489 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5490 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5491 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5492 // however the mov+fmov sequence is always better because of the reduced
5493 // cache pressure. The timings are still the same if you consider
5494 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5495 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5496 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5497 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5498 Insn);
5499 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5500 IsLegal = Insn.size() <= Limit;
5501 }
5502
5503 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5504 << " imm value: "; Imm.dump(););
5505 return IsLegal;
5506}
5507
5508//===----------------------------------------------------------------------===//
5509// AArch64 Optimization Hooks
5510//===----------------------------------------------------------------------===//
5511
5512static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5513 SDValue Operand, SelectionDAG &DAG,
5514 int &ExtraSteps) {
5515 EVT VT = Operand.getValueType();
5516 if (ST->hasNEON() &&
5517 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5518 VT == MVT::f32 || VT == MVT::v1f32 ||
5519 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5520 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5521 // For the reciprocal estimates, convergence is quadratic, so the number
5522 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5523 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5524 // the result for float (23 mantissa bits) is 2 and for double (52
5525 // mantissa bits) is 3.
5526 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5527
5528 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5529 }
5530
5531 return SDValue();
5532}
5533
5534SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5535 SelectionDAG &DAG, int Enabled,
5536 int &ExtraSteps,
5537 bool &UseOneConst,
5538 bool Reciprocal) const {
5539 if (Enabled == ReciprocalEstimate::Enabled ||
5540 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5541 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5542 DAG, ExtraSteps)) {
5543 SDLoc DL(Operand);
5544 EVT VT = Operand.getValueType();
5545
5546 SDNodeFlags Flags;
5547 Flags.setAllowReassociation(true);
5548
5549 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5550 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5551 for (int i = ExtraSteps; i > 0; --i) {
5552 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5553 Flags);
5554 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5555 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5556 }
5557 if (!Reciprocal) {
5558 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5559 VT);
5560 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5561 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5562
5563 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5564 // Correct the result if the operand is 0.0.
5565 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5566 VT, Eq, Operand, Estimate);
5567 }
5568
5569 ExtraSteps = 0;
5570 return Estimate;
5571 }
5572
5573 return SDValue();
5574}
5575
5576SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5577 SelectionDAG &DAG, int Enabled,
5578 int &ExtraSteps) const {
5579 if (Enabled == ReciprocalEstimate::Enabled)
5580 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5581 DAG, ExtraSteps)) {
5582 SDLoc DL(Operand);
5583 EVT VT = Operand.getValueType();
5584
5585 SDNodeFlags Flags;
5586 Flags.setAllowReassociation(true);
5587
5588 // Newton reciprocal iteration: E * (2 - X * E)
5589 // AArch64 reciprocal iteration instruction: (2 - M * N)
5590 for (int i = ExtraSteps; i > 0; --i) {
5591 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5592 Estimate, Flags);
5593 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5594 }
5595
5596 ExtraSteps = 0;
5597 return Estimate;
5598 }
5599
5600 return SDValue();
5601}
5602
5603//===----------------------------------------------------------------------===//
5604// AArch64 Inline Assembly Support
5605//===----------------------------------------------------------------------===//
5606
5607// Table of Constraints
5608// TODO: This is the current set of constraints supported by ARM for the
5609// compiler, not all of them may make sense.
5610//
5611// r - A general register
5612// w - An FP/SIMD register of some size in the range v0-v31
5613// x - An FP/SIMD register of some size in the range v0-v15
5614// I - Constant that can be used with an ADD instruction
5615// J - Constant that can be used with a SUB instruction
5616// K - Constant that can be used with a 32-bit logical instruction
5617// L - Constant that can be used with a 64-bit logical instruction
5618// M - Constant that can be used as a 32-bit MOV immediate
5619// N - Constant that can be used as a 64-bit MOV immediate
5620// Q - A memory reference with base register and no offset
5621// S - A symbolic address
5622// Y - Floating point constant zero
5623// Z - Integer constant zero
5624//
5625// Note that general register operands will be output using their 64-bit x
5626// register name, whatever the size of the variable, unless the asm operand
5627// is prefixed by the %w modifier. Floating-point and SIMD register operands
5628// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5629// %q modifier.
5630const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5631 // At this point, we have to lower this constraint to something else, so we
5632 // lower it to an "r" or "w". However, by doing this we will force the result
5633 // to be in register, while the X constraint is much more permissive.
5634 //
5635 // Although we are correct (we are free to emit anything, without
5636 // constraints), we might break use cases that would expect us to be more
5637 // efficient and emit something else.
5638 if (!Subtarget->hasFPARMv8())
5639 return "r";
5640
5641 if (ConstraintVT.isFloatingPoint())
5642 return "w";
5643
5644 if (ConstraintVT.isVector() &&
5645 (ConstraintVT.getSizeInBits() == 64 ||
5646 ConstraintVT.getSizeInBits() == 128))
5647 return "w";
5648
5649 return "r";
5650}
5651
5652/// getConstraintType - Given a constraint letter, return the type of
5653/// constraint it is for this target.
5654AArch64TargetLowering::ConstraintType
5655AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5656 if (Constraint.size() == 1) {
5657 switch (Constraint[0]) {
5658 default:
5659 break;
5660 case 'z':
5661 return C_Other;
5662 case 'x':
5663 case 'w':
5664 return C_RegisterClass;
5665 // An address with a single base register. Due to the way we
5666 // currently handle addresses it is the same as 'r'.
5667 case 'Q':
5668 return C_Memory;
5669 case 'S': // A symbolic address
5670 return C_Other;
5671 }
5672 }
5673 return TargetLowering::getConstraintType(Constraint);
5674}
5675
5676/// Examine constraint type and operand type and determine a weight value.
5677/// This object must already have been set up with the operand type
5678/// and the current alternative constraint selected.
5679TargetLowering::ConstraintWeight
5680AArch64TargetLowering::getSingleConstraintMatchWeight(
5681 AsmOperandInfo &info, const char *constraint) const {
5682 ConstraintWeight weight = CW_Invalid;
5683 Value *CallOperandVal = info.CallOperandVal;
5684 // If we don't have a value, we can't do a match,
5685 // but allow it at the lowest weight.
5686 if (!CallOperandVal)
5687 return CW_Default;
5688 Type *type = CallOperandVal->getType();
5689 // Look at the constraint type.
5690 switch (*constraint) {
5691 default:
5692 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5693 break;
5694 case 'x':
5695 case 'w':
5696 if (type->isFloatingPointTy() || type->isVectorTy())
5697 weight = CW_Register;
5698 break;
5699 case 'z':
5700 weight = CW_Constant;
5701 break;
5702 }
5703 return weight;
5704}
5705
5706std::pair<unsigned, const TargetRegisterClass *>
5707AArch64TargetLowering::getRegForInlineAsmConstraint(
5708 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5709 if (Constraint.size() == 1) {
5710 switch (Constraint[0]) {
5711 case 'r':
5712 if (VT.getSizeInBits() == 64)
5713 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5714 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5715 case 'w':
5716 if (!Subtarget->hasFPARMv8())
5717 break;
5718 if (VT.getSizeInBits() == 16)
5719 return std::make_pair(0U, &AArch64::FPR16RegClass);
5720 if (VT.getSizeInBits() == 32)
5721 return std::make_pair(0U, &AArch64::FPR32RegClass);
5722 if (VT.getSizeInBits() == 64)
5723 return std::make_pair(0U, &AArch64::FPR64RegClass);
5724 if (VT.getSizeInBits() == 128)
5725 return std::make_pair(0U, &AArch64::FPR128RegClass);
5726 break;
5727 // The instructions that this constraint is designed for can
5728 // only take 128-bit registers so just use that regclass.
5729 case 'x':
5730 if (!Subtarget->hasFPARMv8())
5731 break;
5732 if (VT.getSizeInBits() == 128)
5733 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5734 break;
5735 }
5736 }
5737 if (StringRef("{cc}").equals_lower(Constraint))
5738 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5739
5740 // Use the default implementation in TargetLowering to convert the register
5741 // constraint into a member of a register class.
5742 std::pair<unsigned, const TargetRegisterClass *> Res;
5743 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5744
5745 // Not found as a standard register?
5746 if (!Res.second) {
5747 unsigned Size = Constraint.size();
5748 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5749 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5750 int RegNo;
5751 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5752 if (!Failed && RegNo >= 0 && RegNo <= 31) {
5753 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5754 // By default we'll emit v0-v31 for this unless there's a modifier where
5755 // we'll emit the correct register as well.
5756 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5757 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5758 Res.second = &AArch64::FPR64RegClass;
5759 } else {
5760 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5761 Res.second = &AArch64::FPR128RegClass;
5762 }
5763 }
5764 }
5765 }
5766
5767 if (Res.second && !Subtarget->hasFPARMv8() &&
5768 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5769 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5770 return std::make_pair(0U, nullptr);
5771
5772 return Res;
5773}
5774
5775/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5776/// vector. If it is invalid, don't add anything to Ops.
5777void AArch64TargetLowering::LowerAsmOperandForConstraint(
5778 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5779 SelectionDAG &DAG) const {
5780 SDValue Result;
5781
5782 // Currently only support length 1 constraints.
5783 if (Constraint.length() != 1)
5784 return;
5785
5786 char ConstraintLetter = Constraint[0];
5787 switch (ConstraintLetter) {
5788 default:
5789 break;
5790
5791 // This set of constraints deal with valid constants for various instructions.
5792 // Validate and return a target constant for them if we can.
5793 case 'z': {
5794 // 'z' maps to xzr or wzr so it needs an input of 0.
5795 if (!isNullConstant(Op))
5796 return;
5797
5798 if (Op.getValueType() == MVT::i64)
5799 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5800 else
5801 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5802 break;
5803 }
5804 case 'S': {
5805 // An absolute symbolic address or label reference.
5806 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5807 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5808 GA->getValueType(0));
5809 } else if (const BlockAddressSDNode *BA =
5810 dyn_cast<BlockAddressSDNode>(Op)) {
5811 Result =
5812 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5813 } else if (const ExternalSymbolSDNode *ES =
5814 dyn_cast<ExternalSymbolSDNode>(Op)) {
5815 Result =
5816 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5817 } else
5818 return;
5819 break;
5820 }
5821
5822 case 'I':
5823 case 'J':
5824 case 'K':
5825 case 'L':
5826 case 'M':
5827 case 'N':
5828 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5829 if (!C)
5830 return;
5831
5832 // Grab the value and do some validation.
5833 uint64_t CVal = C->getZExtValue();
5834 switch (ConstraintLetter) {
5835 // The I constraint applies only to simple ADD or SUB immediate operands:
5836 // i.e. 0 to 4095 with optional shift by 12
5837 // The J constraint applies only to ADD or SUB immediates that would be
5838 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5839 // instruction [or vice versa], in other words -1 to -4095 with optional
5840 // left shift by 12.
5841 case 'I':
5842 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5843 break;
5844 return;
5845 case 'J': {
5846 uint64_t NVal = -C->getSExtValue();
5847 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5848 CVal = C->getSExtValue();
5849 break;
5850 }
5851 return;
5852 }
5853 // The K and L constraints apply *only* to logical immediates, including
5854 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5855 // been removed and MOV should be used). So these constraints have to
5856 // distinguish between bit patterns that are valid 32-bit or 64-bit
5857 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5858 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5859 // versa.
5860 case 'K':
5861 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5862 break;
5863 return;
5864 case 'L':
5865 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5866 break;
5867 return;
5868 // The M and N constraints are a superset of K and L respectively, for use
5869 // with the MOV (immediate) alias. As well as the logical immediates they
5870 // also match 32 or 64-bit immediates that can be loaded either using a
5871 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5872 // (M) or 64-bit 0x1234000000000000 (N) etc.
5873 // As a note some of this code is liberally stolen from the asm parser.
5874 case 'M': {
5875 if (!isUInt<32>(CVal))
5876 return;
5877 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5878 break;
5879 if ((CVal & 0xFFFF) == CVal)
5880 break;
5881 if ((CVal & 0xFFFF0000ULL) == CVal)
5882 break;
5883 uint64_t NCVal = ~(uint32_t)CVal;
5884 if ((NCVal & 0xFFFFULL) == NCVal)
5885 break;
5886 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5887 break;
5888 return;
5889 }
5890 case 'N': {
5891 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5892 break;
5893 if ((CVal & 0xFFFFULL) == CVal)
5894 break;
5895 if ((CVal & 0xFFFF0000ULL) == CVal)
5896 break;
5897 if ((CVal & 0xFFFF00000000ULL) == CVal)
5898 break;
5899 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5900 break;
5901 uint64_t NCVal = ~CVal;
5902 if ((NCVal & 0xFFFFULL) == NCVal)
5903 break;
5904 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5905 break;
5906 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5907 break;
5908 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5909 break;
5910 return;
5911 }
5912 default:
5913 return;
5914 }
5915
5916 // All assembler immediates are 64-bit integers.
5917 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5918 break;
5919 }
5920
5921 if (Result.getNode()) {
5922 Ops.push_back(Result);
5923 return;
5924 }
5925
5926 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5927}
5928
5929//===----------------------------------------------------------------------===//
5930// AArch64 Advanced SIMD Support
5931//===----------------------------------------------------------------------===//
5932
5933/// WidenVector - Given a value in the V64 register class, produce the
5934/// equivalent value in the V128 register class.
5935static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5936 EVT VT = V64Reg.getValueType();
5937 unsigned NarrowSize = VT.getVectorNumElements();
5938 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5939 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5940 SDLoc DL(V64Reg);
5941
5942 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5943 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5944}
5945
5946/// getExtFactor - Determine the adjustment factor for the position when
5947/// generating an "extract from vector registers" instruction.
5948static unsigned getExtFactor(SDValue &V) {
5949 EVT EltType = V.getValueType().getVectorElementType();
5950 return EltType.getSizeInBits() / 8;
5951}
5952
5953/// NarrowVector - Given a value in the V128 register class, produce the
5954/// equivalent value in the V64 register class.
5955static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5956 EVT VT = V128Reg.getValueType();
5957 unsigned WideSize = VT.getVectorNumElements();
5958 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5959 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5960 SDLoc DL(V128Reg);
5961
5962 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5963}
5964
5965// Gather data to see if the operation can be modelled as a
5966// shuffle in combination with VEXTs.
5967SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5968 SelectionDAG &DAG) const {
5969 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5970 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
5971 SDLoc dl(Op);
5972 EVT VT = Op.getValueType();
5973 unsigned NumElts = VT.getVectorNumElements();
5974
5975 struct ShuffleSourceInfo {
5976 SDValue Vec;
5977 unsigned MinElt;
5978 unsigned MaxElt;
5979
5980 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5981 // be compatible with the shuffle we intend to construct. As a result
5982 // ShuffleVec will be some sliding window into the original Vec.
5983 SDValue ShuffleVec;
5984
5985 // Code should guarantee that element i in Vec starts at element "WindowBase
5986 // + i * WindowScale in ShuffleVec".
5987 int WindowBase;
5988 int WindowScale;
5989
5990 ShuffleSourceInfo(SDValue Vec)
5991 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5992 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5993
5994 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5995 };
5996
5997 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5998 // node.
5999 SmallVector<ShuffleSourceInfo, 2> Sources;
6000 for (unsigned i = 0; i < NumElts; ++i) {
6001 SDValue V = Op.getOperand(i);
6002 if (V.isUndef())
6003 continue;
6004 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6005 !isa<ConstantSDNode>(V.getOperand(1))) {
6006 LLVM_DEBUG(
6007 dbgs() << "Reshuffle failed: "
6008 "a shuffle can only come from building a vector from "
6009 "various elements of other vectors, provided their "
6010 "indices are constant\n");
6011 return SDValue();
6012 }
6013
6014 // Add this element source to the list if it's not already there.
6015 SDValue SourceVec = V.getOperand(0);
6016 auto Source = find(Sources, SourceVec);
6017 if (Source == Sources.end())
6018 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6019
6020 // Update the minimum and maximum lane number seen.
6021 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6022 Source->MinElt = std::min(Source->MinElt, EltNo);
6023 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6024 }
6025
6026 if (Sources.size() > 2) {
6027 LLVM_DEBUG(
6028 dbgs() << "Reshuffle failed: currently only do something sane when at "
6029 "most two source vectors are involved\n");
6030 return SDValue();
6031 }
6032
6033 // Find out the smallest element size among result and two sources, and use
6034 // it as element size to build the shuffle_vector.
6035 EVT SmallestEltTy = VT.getVectorElementType();
6036 for (auto &Source : Sources) {
6037 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6038 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6039 SmallestEltTy = SrcEltTy;
6040 }
6041 }
6042 unsigned ResMultiplier =
6043 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6044 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6045 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6046
6047 // If the source vector is too wide or too narrow, we may nevertheless be able
6048 // to construct a compatible shuffle either by concatenating it with UNDEF or
6049 // extracting a suitable range of elements.
6050 for (auto &Src : Sources) {
6051 EVT SrcVT = Src.ShuffleVec.getValueType();
6052
6053 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6054 continue;
6055
6056 // This stage of the search produces a source with the same element type as
6057 // the original, but with a total width matching the BUILD_VECTOR output.
6058 EVT EltVT = SrcVT.getVectorElementType();
6059 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6060 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6061
6062 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6063 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6064 // We can pad out the smaller vector for free, so if it's part of a
6065 // shuffle...
6066 Src.ShuffleVec =
6067 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6068 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6069 continue;
6070 }
6071
6072 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6073
6074 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6075 LLVM_DEBUG(
6076 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6077 return SDValue();
6078 }
6079
6080 if (Src.MinElt >= NumSrcElts) {
6081 // The extraction can just take the second half
6082 Src.ShuffleVec =
6083 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6084 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6085 Src.WindowBase = -NumSrcElts;
6086 } else if (Src.MaxElt < NumSrcElts) {
6087 // The extraction can just take the first half
6088 Src.ShuffleVec =
6089 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6090 DAG.getConstant(0, dl, MVT::i64));
6091 } else {
6092 // An actual VEXT is needed
6093 SDValue VEXTSrc1 =
6094 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6095 DAG.getConstant(0, dl, MVT::i64));
6096 SDValue VEXTSrc2 =
6097 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6098 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6099 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6100
6101 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6102 VEXTSrc2,
6103 DAG.getConstant(Imm, dl, MVT::i32));
6104 Src.WindowBase = -Src.MinElt;
6105 }
6106 }
6107
6108 // Another possible incompatibility occurs from the vector element types. We
6109 // can fix this by bitcasting the source vectors to the same type we intend
6110 // for the shuffle.
6111 for (auto &Src : Sources) {
6112 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6113 if (SrcEltTy == SmallestEltTy)
6114 continue;
6115 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6116 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6117 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6118 Src.WindowBase *= Src.WindowScale;
6119 }
6120
6121 // Final sanity check before we try to actually produce a shuffle.
6122 LLVM_DEBUG(for (auto Src
6123 : Sources)
6124 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6125
6126 // The stars all align, our next step is to produce the mask for the shuffle.
6127 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6128 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6129 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6130 SDValue Entry = Op.getOperand(i);
6131 if (Entry.isUndef())
6132 continue;
6133
6134 auto Src = find(Sources, Entry.getOperand(0));
6135 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6136
6137 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6138 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6139 // segment.
6140 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6141 int BitsDefined =
6142 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6143 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6144
6145 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6146 // starting at the appropriate offset.
6147 int *LaneMask = &Mask[i * ResMultiplier];
6148
6149 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6150 ExtractBase += NumElts * (Src - Sources.begin());
6151 for (int j = 0; j < LanesDefined; ++j)
6152 LaneMask[j] = ExtractBase + j;
6153 }
6154
6155 // Final check before we try to produce nonsense...
6156 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6157 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6158 return SDValue();
6159 }
6160
6161 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6162 for (unsigned i = 0; i < Sources.size(); ++i)
6163 ShuffleOps[i] = Sources[i].ShuffleVec;
6164
6165 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6166 ShuffleOps[1], Mask);
6167 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6168
6169 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6170 dbgs() << "Reshuffle, creating node: "; V.dump(););
6171
6172 return V;
6173}
6174
6175// check if an EXT instruction can handle the shuffle mask when the
6176// vector sources of the shuffle are the same.
6177static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6178 unsigned NumElts = VT.getVectorNumElements();
6179
6180 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6181 if (M[0] < 0)
6182 return false;
6183
6184 Imm = M[0];
6185
6186 // If this is a VEXT shuffle, the immediate value is the index of the first
6187 // element. The other shuffle indices must be the successive elements after
6188 // the first one.
6189 unsigned ExpectedElt = Imm;
6190 for (unsigned i = 1; i < NumElts; ++i) {
6191 // Increment the expected index. If it wraps around, just follow it
6192 // back to index zero and keep going.
6193 ++ExpectedElt;
6194 if (ExpectedElt == NumElts)
6195 ExpectedElt = 0;
6196
6197 if (M[i] < 0)
6198 continue; // ignore UNDEF indices
6199 if (ExpectedElt != static_cast<unsigned>(M[i]))
6200 return false;
6201 }
6202
6203 return true;
6204}
6205
6206// check if an EXT instruction can handle the shuffle mask when the
6207// vector sources of the shuffle are different.
6208static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6209 unsigned &Imm) {
6210 // Look for the first non-undef element.
6211 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6212
6213 // Benefit form APInt to handle overflow when calculating expected element.
6214 unsigned NumElts = VT.getVectorNumElements();
6215 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6216 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6217 // The following shuffle indices must be the successive elements after the
6218 // first real element.
6219 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6220 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6221 if (FirstWrongElt != M.end())
6222 return false;
6223
6224 // The index of an EXT is the first element if it is not UNDEF.
6225 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6226 // value of the first element. E.g.
6227 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6228 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6229 // ExpectedElt is the last mask index plus 1.
6230 Imm = ExpectedElt.getZExtValue();
6231
6232 // There are two difference cases requiring to reverse input vectors.
6233 // For example, for vector <4 x i32> we have the following cases,
6234 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6235 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6236 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6237 // to reverse two input vectors.
6238 if (Imm < NumElts)
6239 ReverseEXT = true;
6240 else
6241 Imm -= NumElts;
6242
6243 return true;
6244}
6245
6246/// isREVMask - Check if a vector shuffle corresponds to a REV
6247/// instruction with the specified blocksize. (The order of the elements
6248/// within each block of the vector is reversed.)
6249static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6250 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6251 "Only possible block sizes for REV are: 16, 32, 64");
6252
6253 unsigned EltSz = VT.getScalarSizeInBits();
6254 if (EltSz == 64)
6255 return false;
6256
6257 unsigned NumElts = VT.getVectorNumElements();
6258 unsigned BlockElts = M[0] + 1;
6259 // If the first shuffle index is UNDEF, be optimistic.
6260 if (M[0] < 0)
6261 BlockElts = BlockSize / EltSz;
6262
6263 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6264 return false;
6265
6266 for (unsigned i = 0; i < NumElts; ++i) {
6267 if (M[i] < 0)
6268 continue; // ignore UNDEF indices
6269 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6270 return false;
6271 }
6272
6273 return true;
6274}
6275
6276static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6277 unsigned NumElts = VT.getVectorNumElements();
6278 WhichResult = (M[0] == 0 ? 0 : 1);
6279 unsigned Idx = WhichResult * NumElts / 2;
6280 for (unsigned i = 0; i != NumElts; i += 2) {
6281 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6282 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6283 return false;
6284 Idx += 1;
6285 }
6286
6287 return true;
6288}
6289
6290static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6291 unsigned NumElts = VT.getVectorNumElements();
6292 WhichResult = (M[0] == 0 ? 0 : 1);
6293 for (unsigned i = 0; i != NumElts; ++i) {
6294 if (M[i] < 0)
6295 continue; // ignore UNDEF indices
6296 if ((unsigned)M[i] != 2 * i + WhichResult)
6297 return false;
6298 }
6299
6300 return true;
6301}
6302
6303static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6304 unsigned NumElts = VT.getVectorNumElements();
6305 if (NumElts % 2 != 0)
6306 return false;
6307 WhichResult = (M[0] == 0 ? 0 : 1);
6308 for (unsigned i = 0; i < NumElts; i += 2) {
6309 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6310 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6311 return false;
6312 }
6313 return true;
6314}
6315
6316/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6317/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6318/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6319static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6320 unsigned NumElts = VT.getVectorNumElements();
6321 if (NumElts % 2 != 0)
6322 return false;
6323 WhichResult = (M[0] == 0 ? 0 : 1);
6324 unsigned Idx = WhichResult * NumElts / 2;
6325 for (unsigned i = 0; i != NumElts; i += 2) {
6326 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6327 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6328 return false;
6329 Idx += 1;
6330 }
6331
6332 return true;
6333}
6334
6335/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6336/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6337/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6338static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6339 unsigned Half = VT.getVectorNumElements() / 2;
6340 WhichResult = (M[0] == 0 ? 0 : 1);
6341 for (unsigned j = 0; j != 2; ++j) {
6342 unsigned Idx = WhichResult;
6343 for (unsigned i = 0; i != Half; ++i) {
6344 int MIdx = M[i + j * Half];
6345 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6346 return false;
6347 Idx += 2;
6348 }
6349 }
6350
6351 return true;
6352}
6353
6354/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6355/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6356/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6357static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6358 unsigned NumElts = VT.getVectorNumElements();
6359 if (NumElts % 2 != 0)
6360 return false;
6361 WhichResult = (M[0] == 0 ? 0 : 1);
6362 for (unsigned i = 0; i < NumElts; i += 2) {
6363 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6364 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6365 return false;
6366 }
6367 return true;
6368}
6369
6370static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6371 bool &DstIsLeft, int &Anomaly) {
6372 if (M.size() != static_cast<size_t>(NumInputElements))
6373 return false;
6374
6375 int NumLHSMatch = 0, NumRHSMatch = 0;
6376 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6377
6378 for (int i = 0; i < NumInputElements; ++i) {
6379 if (M[i] == -1) {
6380 ++NumLHSMatch;
6381 ++NumRHSMatch;
6382 continue;
6383 }
6384
6385 if (M[i] == i)
6386 ++NumLHSMatch;
6387 else
6388 LastLHSMismatch = i;
6389
6390 if (M[i] == i + NumInputElements)
6391 ++NumRHSMatch;
6392 else
6393 LastRHSMismatch = i;
6394 }
6395
6396 if (NumLHSMatch == NumInputElements - 1) {
6397 DstIsLeft = true;
6398 Anomaly = LastLHSMismatch;
6399 return true;
6400 } else if (NumRHSMatch == NumInputElements - 1) {
6401 DstIsLeft = false;
6402 Anomaly = LastRHSMismatch;
6403 return true;
6404 }
6405
6406 return false;
6407}
6408
6409static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6410 if (VT.getSizeInBits() != 128)
6411 return false;
6412
6413 unsigned NumElts = VT.getVectorNumElements();
6414
6415 for (int I = 0, E = NumElts / 2; I != E; I++) {
6416 if (Mask[I] != I)
6417 return false;
6418 }
6419
6420 int Offset = NumElts / 2;
6421 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6422 if (Mask[I] != I + SplitLHS * Offset)
6423 return false;
6424 }
6425
6426 return true;
6427}
6428
6429static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6430 SDLoc DL(Op);
6431 EVT VT = Op.getValueType();
6432 SDValue V0 = Op.getOperand(0);
6433 SDValue V1 = Op.getOperand(1);
6434 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6435
6436 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6437 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6438 return SDValue();
6439
6440 bool SplitV0 = V0.getValueSizeInBits() == 128;
6441
6442 if (!isConcatMask(Mask, VT, SplitV0))
6443 return SDValue();
6444
6445 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6446 VT.getVectorNumElements() / 2);
6447 if (SplitV0) {
6448 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6449 DAG.getConstant(0, DL, MVT::i64));
6450 }
6451 if (V1.getValueSizeInBits() == 128) {
6452 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6453 DAG.getConstant(0, DL, MVT::i64));
6454 }
6455 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6456}
6457
6458/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6459/// the specified operations to build the shuffle.
6460static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6461 SDValue RHS, SelectionDAG &DAG,
6462 const SDLoc &dl) {
6463 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6464 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6465 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6466
6467 enum {
6468 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6469 OP_VREV,
6470 OP_VDUP0,
6471 OP_VDUP1,
6472 OP_VDUP2,
6473 OP_VDUP3,
6474 OP_VEXT1,
6475 OP_VEXT2,
6476 OP_VEXT3,
6477 OP_VUZPL, // VUZP, left result
6478 OP_VUZPR, // VUZP, right result
6479 OP_VZIPL, // VZIP, left result
6480 OP_VZIPR, // VZIP, right result
6481 OP_VTRNL, // VTRN, left result
6482 OP_VTRNR // VTRN, right result
6483 };
6484
6485 if (OpNum == OP_COPY) {
6486 if (LHSID == (1 * 9 + 2) * 9 + 3)
6487 return LHS;
6488 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6489 return RHS;
6490 }
6491
6492 SDValue OpLHS, OpRHS;
6493 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6494 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6495 EVT VT = OpLHS.getValueType();
6496
6497 switch (OpNum) {
6498 default:
6499 llvm_unreachable("Unknown shuffle opcode!");
6500 case OP_VREV:
6501 // VREV divides the vector in half and swaps within the half.
6502 if (VT.getVectorElementType() == MVT::i32 ||
6503 VT.getVectorElementType() == MVT::f32)
6504 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6505 // vrev <4 x i16> -> REV32
6506 if (VT.getVectorElementType() == MVT::i16 ||
6507 VT.getVectorElementType() == MVT::f16)
6508 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6509 // vrev <4 x i8> -> REV16
6510 assert(VT.getVectorElementType() == MVT::i8);
6511 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6512 case OP_VDUP0:
6513 case OP_VDUP1:
6514 case OP_VDUP2:
6515 case OP_VDUP3: {
6516 EVT EltTy = VT.getVectorElementType();
6517 unsigned Opcode;
6518 if (EltTy == MVT::i8)
6519 Opcode = AArch64ISD::DUPLANE8;
6520 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6521 Opcode = AArch64ISD::DUPLANE16;
6522 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6523 Opcode = AArch64ISD::DUPLANE32;
6524 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6525 Opcode = AArch64ISD::DUPLANE64;
6526 else
6527 llvm_unreachable("Invalid vector element type?");
6528
6529 if (VT.getSizeInBits() == 64)
6530 OpLHS = WidenVector(OpLHS, DAG);
6531 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6532 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6533 }
6534 case OP_VEXT1:
6535 case OP_VEXT2:
6536 case OP_VEXT3: {
6537 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6538 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6539 DAG.getConstant(Imm, dl, MVT::i32));
6540 }
6541 case OP_VUZPL:
6542 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6543 OpRHS);
6544 case OP_VUZPR:
6545 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6546 OpRHS);
6547 case OP_VZIPL:
6548 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6549 OpRHS);
6550 case OP_VZIPR:
6551 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6552 OpRHS);
6553 case OP_VTRNL:
6554 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6555 OpRHS);
6556 case OP_VTRNR:
6557 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6558 OpRHS);
6559 }
6560}
6561
6562static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6563 SelectionDAG &DAG) {
6564 // Check to see if we can use the TBL instruction.
6565 SDValue V1 = Op.getOperand(0);
6566 SDValue V2 = Op.getOperand(1);
6567 SDLoc DL(Op);
6568
6569 EVT EltVT = Op.getValueType().getVectorElementType();
6570 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6571
6572 SmallVector<SDValue, 8> TBLMask;
6573 for (int Val : ShuffleMask) {
6574 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6575 unsigned Offset = Byte + Val * BytesPerElt;
6576 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6577 }
6578 }
6579
6580 MVT IndexVT = MVT::v8i8;
6581 unsigned IndexLen = 8;
6582 if (Op.getValueSizeInBits() == 128) {
6583 IndexVT = MVT::v16i8;
6584 IndexLen = 16;
6585 }
6586
6587 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6588 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6589
6590 SDValue Shuffle;
6591 if (V2.getNode()->isUndef()) {
6592 if (IndexLen == 8)
6593 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6594 Shuffle = DAG.getNode(
6595 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6596 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6597 DAG.getBuildVector(IndexVT, DL,
6598 makeArrayRef(TBLMask.data(), IndexLen)));
6599 } else {
6600 if (IndexLen == 8) {
6601 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6602 Shuffle = DAG.getNode(
6603 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6604 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6605 DAG.getBuildVector(IndexVT, DL,
6606 makeArrayRef(TBLMask.data(), IndexLen)));
6607 } else {
6608 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6609 // cannot currently represent the register constraints on the input
6610 // table registers.
6611 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6612 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6613 // IndexLen));
6614 Shuffle = DAG.getNode(
6615 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6616 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6617 V2Cst, DAG.getBuildVector(IndexVT, DL,
6618 makeArrayRef(TBLMask.data(), IndexLen)));
6619 }
6620 }
6621 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6622}
6623
6624static unsigned getDUPLANEOp(EVT EltType) {
6625 if (EltType == MVT::i8)
6626 return AArch64ISD::DUPLANE8;
6627 if (EltType == MVT::i16 || EltType == MVT::f16)
6628 return AArch64ISD::DUPLANE16;
6629 if (EltType == MVT::i32 || EltType == MVT::f32)
6630 return AArch64ISD::DUPLANE32;
6631 if (EltType == MVT::i64 || EltType == MVT::f64)
6632 return AArch64ISD::DUPLANE64;
6633
6634 llvm_unreachable("Invalid vector element type?");
6635}
6636
6637SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6638 SelectionDAG &DAG) const {
6639 SDLoc dl(Op);
6640 EVT VT = Op.getValueType();
6641
6642 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6643
6644 // Convert shuffles that are directly supported on NEON to target-specific
6645 // DAG nodes, instead of keeping them as shuffles and matching them again
6646 // during code selection. This is more efficient and avoids the possibility
6647 // of inconsistencies between legalization and selection.
6648 ArrayRef<int> ShuffleMask = SVN->getMask();
6649
6650 SDValue V1 = Op.getOperand(0);
6651 SDValue V2 = Op.getOperand(1);
6652
6653 if (SVN->isSplat()) {
6654 int Lane = SVN->getSplatIndex();
6655 // If this is undef splat, generate it via "just" vdup, if possible.
6656 if (Lane == -1)
6657 Lane = 0;
6658
6659 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6660 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6661 V1.getOperand(0));
6662 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6663 // constant. If so, we can just reference the lane's definition directly.
6664 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6665 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6666 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6667
6668 // Otherwise, duplicate from the lane of the input vector.
6669 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6670
6671 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6672 // to make a vector of the same size as this SHUFFLE. We can ignore the
6673 // extract entirely, and canonicalise the concat using WidenVector.
6674 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6675 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6676 V1 = V1.getOperand(0);
6677 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6678 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6679 Lane -= Idx * VT.getVectorNumElements() / 2;
6680 V1 = WidenVector(V1.getOperand(Idx), DAG);
6681 } else if (VT.getSizeInBits() == 64)
6682 V1 = WidenVector(V1, DAG);
6683
6684 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6685 }
6686
6687 if (isREVMask(ShuffleMask, VT, 64))
6688 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6689 if (isREVMask(ShuffleMask, VT, 32))
6690 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6691 if (isREVMask(ShuffleMask, VT, 16))
6692 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6693
6694 bool ReverseEXT = false;
6695 unsigned Imm;
6696 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6697 if (ReverseEXT)
6698 std::swap(V1, V2);
6699 Imm *= getExtFactor(V1);
6700 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6701 DAG.getConstant(Imm, dl, MVT::i32));
6702 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6703 Imm *= getExtFactor(V1);
6704 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6705 DAG.getConstant(Imm, dl, MVT::i32));
6706 }
6707
6708 unsigned WhichResult;
6709 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6710 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6711 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6712 }
6713 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6714 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6715 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6716 }
6717 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6718 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6719 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6720 }
6721
6722 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6723 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6724 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6725 }
6726 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6727 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6728 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6729 }
6730 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6731 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6732 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6733 }
6734
6735 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6736 return Concat;
6737
6738 bool DstIsLeft;
6739 int Anomaly;
6740 int NumInputElements = V1.getValueType().getVectorNumElements();
6741 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6742 SDValue DstVec = DstIsLeft ? V1 : V2;
6743 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6744
6745 SDValue SrcVec = V1;
6746 int SrcLane = ShuffleMask[Anomaly];
6747 if (SrcLane >= NumInputElements) {
6748 SrcVec = V2;
6749 SrcLane -= VT.getVectorNumElements();
6750 }
6751 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6752
6753 EVT ScalarVT = VT.getVectorElementType();
6754
6755 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6756 ScalarVT = MVT::i32;
6757
6758 return DAG.getNode(
6759 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6760 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6761 DstLaneV);
6762 }
6763
6764 // If the shuffle is not directly supported and it has 4 elements, use
6765 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6766 unsigned NumElts = VT.getVectorNumElements();
6767 if (NumElts == 4) {
6768 unsigned PFIndexes[4];
6769 for (unsigned i = 0; i != 4; ++i) {
6770 if (ShuffleMask[i] < 0)
6771 PFIndexes[i] = 8;
6772 else
6773 PFIndexes[i] = ShuffleMask[i];
6774 }
6775
6776 // Compute the index in the perfect shuffle table.
6777 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6778 PFIndexes[2] * 9 + PFIndexes[3];
6779 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6780 unsigned Cost = (PFEntry >> 30);
6781
6782 if (Cost <= 4)
6783 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6784 }
6785
6786 return GenerateTBL(Op, ShuffleMask, DAG);
6787}
6788
6789static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6790 APInt &UndefBits) {
6791 EVT VT = BVN->getValueType(0);
6792 APInt SplatBits, SplatUndef;
6793 unsigned SplatBitSize;
6794 bool HasAnyUndefs;
6795 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6796 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6797
6798 for (unsigned i = 0; i < NumSplats; ++i) {
6799 CnstBits <<= SplatBitSize;
6800 UndefBits <<= SplatBitSize;
6801 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6802 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6803 }
6804
6805 return true;
6806 }
6807
6808 return false;
6809}
6810
6811// Try 64-bit splatted SIMD immediate.
6812static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6813 const APInt &Bits) {
6814 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6815 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6816 EVT VT = Op.getValueType();
6817 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6818
6819 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6820 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6821
6822 SDLoc dl(Op);
6823 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6824 DAG.getConstant(Value, dl, MVT::i32));
6825 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6826 }
6827 }
6828
6829 return SDValue();
6830}
6831
6832// Try 32-bit splatted SIMD immediate.
6833static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6834 const APInt &Bits,
6835 const SDValue *LHS = nullptr) {
6836 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6837 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6838 EVT VT = Op.getValueType();
6839 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6840 bool isAdvSIMDModImm = false;
6841 uint64_t Shift;
6842
6843 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6844 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6845 Shift = 0;
6846 }
6847 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6848 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6849 Shift = 8;
6850 }
6851 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6852 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6853 Shift = 16;
6854 }
6855 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6856 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6857 Shift = 24;
6858 }
6859
6860 if (isAdvSIMDModImm) {
6861 SDLoc dl(Op);
6862 SDValue Mov;
6863
6864 if (LHS)
6865 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6866 DAG.getConstant(Value, dl, MVT::i32),
6867 DAG.getConstant(Shift, dl, MVT::i32));
6868 else
6869 Mov = DAG.getNode(NewOp, dl, MovTy,
6870 DAG.getConstant(Value, dl, MVT::i32),
6871 DAG.getConstant(Shift, dl, MVT::i32));
6872
6873 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6874 }
6875 }
6876
6877 return SDValue();
6878}
6879
6880// Try 16-bit splatted SIMD immediate.
6881static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6882 const APInt &Bits,
6883 const SDValue *LHS = nullptr) {
6884 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6885 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6886 EVT VT = Op.getValueType();
6887 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6888 bool isAdvSIMDModImm = false;
6889 uint64_t Shift;
6890
6891 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6892 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6893 Shift = 0;
6894 }
6895 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6896 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6897 Shift = 8;
6898 }
6899
6900 if (isAdvSIMDModImm) {
6901 SDLoc dl(Op);
6902 SDValue Mov;
6903
6904 if (LHS)
6905 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6906 DAG.getConstant(Value, dl, MVT::i32),
6907 DAG.getConstant(Shift, dl, MVT::i32));
6908 else
6909 Mov = DAG.getNode(NewOp, dl, MovTy,
6910 DAG.getConstant(Value, dl, MVT::i32),
6911 DAG.getConstant(Shift, dl, MVT::i32));
6912
6913 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6914 }
6915 }
6916
6917 return SDValue();
6918}
6919
6920// Try 32-bit splatted SIMD immediate with shifted ones.
6921static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
6922 SelectionDAG &DAG, const APInt &Bits) {
6923 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6924 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6925 EVT VT = Op.getValueType();
6926 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6927 bool isAdvSIMDModImm = false;
6928 uint64_t Shift;
6929
6930 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
6931 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
6932 Shift = 264;
6933 }
6934 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
6935 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
6936 Shift = 272;
6937 }
6938
6939 if (isAdvSIMDModImm) {
6940 SDLoc dl(Op);
6941 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6942 DAG.getConstant(Value, dl, MVT::i32),
6943 DAG.getConstant(Shift, dl, MVT::i32));
6944 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6945 }
6946 }
6947
6948 return SDValue();
6949}
6950
6951// Try 8-bit splatted SIMD immediate.
6952static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6953 const APInt &Bits) {
6954 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6955 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6956 EVT VT = Op.getValueType();
6957 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6958
6959 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
6960 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
6961
6962 SDLoc dl(Op);
6963 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6964 DAG.getConstant(Value, dl, MVT::i32));
6965 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6966 }
6967 }
6968
6969 return SDValue();
6970}
6971
6972// Try FP splatted SIMD immediate.
6973static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6974 const APInt &Bits) {
6975 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6976 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6977 EVT VT = Op.getValueType();
6978 bool isWide = (VT.getSizeInBits() == 128);
6979 MVT MovTy;
6980 bool isAdvSIMDModImm = false;
6981
6982 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
6983 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
6984 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
6985 }
6986 else if (isWide &&
6987 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
6988 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
6989 MovTy = MVT::v2f64;
6990 }
6991
6992 if (isAdvSIMDModImm) {
6993 SDLoc dl(Op);
6994 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6995 DAG.getConstant(Value, dl, MVT::i32));
6996 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6997 }
6998 }
6999
7000 return SDValue();
7001}
7002
7003// Specialized code to quickly find if PotentialBVec is a BuildVector that
7004// consists of only the same constant int value, returned in reference arg
7005// ConstVal
7006static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7007 uint64_t &ConstVal) {
7008 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7009 if (!Bvec)
7010 return false;
7011 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7012 if (!FirstElt)
7013 return false;
7014 EVT VT = Bvec->getValueType(0);
7015 unsigned NumElts = VT.getVectorNumElements();
7016 for (unsigned i = 1; i < NumElts; ++i)
7017 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7018 return false;
7019 ConstVal = FirstElt->getZExtValue();
7020 return true;
7021}
7022
7023static unsigned getIntrinsicID(const SDNode *N) {
7024 unsigned Opcode = N->getOpcode();
7025 switch (Opcode) {
7026 default:
7027 return Intrinsic::not_intrinsic;
7028 case ISD::INTRINSIC_WO_CHAIN: {
7029 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7030 if (IID < Intrinsic::num_intrinsics)
7031 return IID;
7032 return Intrinsic::not_intrinsic;
7033 }
7034 }
7035}
7036
7037// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7038// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7039// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7040// Also, logical shift right -> sri, with the same structure.
7041static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7042 EVT VT = N->getValueType(0);
7043
7044 if (!VT.isVector())
7045 return SDValue();
7046
7047 SDLoc DL(N);
7048
7049 // Is the first op an AND?
7050 const SDValue And = N->getOperand(0);
7051 if (And.getOpcode() != ISD::AND)
7052 return SDValue();
7053
7054 // Is the second op an shl or lshr?
7055 SDValue Shift = N->getOperand(1);
7056 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7057 // or AArch64ISD::VLSHR vector, #shift
7058 unsigned ShiftOpc = Shift.getOpcode();
7059 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7060 return SDValue();
7061 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7062
7063 // Is the shift amount constant?
7064 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7065 if (!C2node)
7066 return SDValue();
7067
7068 // Is the and mask vector all constant?
7069 uint64_t C1;
7070 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7071 return SDValue();
7072
7073 // Is C1 == ~C2, taking into account how much one can shift elements of a
7074 // particular size?
7075 uint64_t C2 = C2node->getZExtValue();
7076 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7077 if (C2 > ElemSizeInBits)
7078 return SDValue();
7079 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7080 if ((C1 & ElemMask) != (~C2 & ElemMask))
7081 return SDValue();
7082
7083 SDValue X = And.getOperand(0);
7084 SDValue Y = Shift.getOperand(0);
7085
7086 unsigned Intrin =
7087 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7088 SDValue ResultSLI =
7089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7090 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7091 Shift.getOperand(1));
7092
7093 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7094 LLVM_DEBUG(N->dump(&DAG));
7095 LLVM_DEBUG(dbgs() << "into: \n");
7096 LLVM_DEBUG(ResultSLI->dump(&DAG));
7097
7098 ++NumShiftInserts;
7099 return ResultSLI;
7100}
7101
7102SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7103 SelectionDAG &DAG) const {
7104 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7105 if (EnableAArch64SlrGeneration) {
7106 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7107 return Res;
7108 }
7109
7110 EVT VT = Op.getValueType();
7111
7112 SDValue LHS = Op.getOperand(0);
7113 BuildVectorSDNode *BVN =
7114 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7115 if (!BVN) {
7116 // OR commutes, so try swapping the operands.
7117 LHS = Op.getOperand(1);
7118 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7119 }
7120 if (!BVN)
7121 return Op;
7122
7123 APInt DefBits(VT.getSizeInBits(), 0);
7124 APInt UndefBits(VT.getSizeInBits(), 0);
7125 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7126 SDValue NewOp;
7127
7128 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7129 DefBits, &LHS)) ||
7130 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7131 DefBits, &LHS)))
7132 return NewOp;
7133
7134 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7135 UndefBits, &LHS)) ||
7136 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7137 UndefBits, &LHS)))
7138 return NewOp;
7139 }
7140
7141 // We can always fall back to a non-immediate OR.
7142 return Op;
7143}
7144
7145// Normalize the operands of BUILD_VECTOR. The value of constant operands will
7146// be truncated to fit element width.
7147static SDValue NormalizeBuildVector(SDValue Op,
7148 SelectionDAG &DAG) {
7149 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7150 SDLoc dl(Op);
7151 EVT VT = Op.getValueType();
7152 EVT EltTy= VT.getVectorElementType();
7153
7154 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7155 return Op;
7156
7157 SmallVector<SDValue, 16> Ops;
7158 for (SDValue Lane : Op->ops()) {
7159 // For integer vectors, type legalization would have promoted the
7160 // operands already. Otherwise, if Op is a floating-point splat
7161 // (with operands cast to integers), then the only possibilities
7162 // are constants and UNDEFs.
7163 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7164 APInt LowBits(EltTy.getSizeInBits(),
7165 CstLane->getZExtValue());
7166 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7167 } else if (Lane.getNode()->isUndef()) {
7168 Lane = DAG.getUNDEF(MVT::i32);
7169 } else {
7170 assert(Lane.getValueType() == MVT::i32 &&
7171 "Unexpected BUILD_VECTOR operand type");
7172 }
7173 Ops.push_back(Lane);
7174 }
7175 return DAG.getBuildVector(VT, dl, Ops);
7176}
7177
7178static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7179 EVT VT = Op.getValueType();
7180
7181 APInt DefBits(VT.getSizeInBits(), 0);
7182 APInt UndefBits(VT.getSizeInBits(), 0);
7183 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7184 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7185 SDValue NewOp;
7186 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7187 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7188 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7189 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7190 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7191 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7192 return NewOp;
7193
7194 DefBits = ~DefBits;
7195 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7196 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7197 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7198 return NewOp;
7199
7200 DefBits = UndefBits;
7201 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7202 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7203 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7204 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7205 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7206 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7207 return NewOp;
7208
7209 DefBits = ~UndefBits;
7210 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7211 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7212 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7213 return NewOp;
7214 }
7215
7216 return SDValue();
7217}
7218
7219SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7220 SelectionDAG &DAG) const {
7221 EVT VT = Op.getValueType();
7222
7223 // Try to build a simple constant vector.
7224 Op = NormalizeBuildVector(Op, DAG);
7225 if (VT.isInteger()) {
7226 // Certain vector constants, used to express things like logical NOT and
7227 // arithmetic NEG, are passed through unmodified. This allows special
7228 // patterns for these operations to match, which will lower these constants
7229 // to whatever is proven necessary.
7230 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7231 if (BVN->isConstant())
7232 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7233 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7234 APInt Val(BitSize,
7235 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7236 if (Val.isNullValue() || Val.isAllOnesValue())
7237 return Op;
7238 }
7239 }
7240
7241 if (SDValue V = ConstantBuildVector(Op, DAG))
7242 return V;
7243
7244 // Scan through the operands to find some interesting properties we can
7245 // exploit:
7246 // 1) If only one value is used, we can use a DUP, or
7247 // 2) if only the low element is not undef, we can just insert that, or
7248 // 3) if only one constant value is used (w/ some non-constant lanes),
7249 // we can splat the constant value into the whole vector then fill
7250 // in the non-constant lanes.
7251 // 4) FIXME: If different constant values are used, but we can intelligently
7252 // select the values we'll be overwriting for the non-constant
7253 // lanes such that we can directly materialize the vector
7254 // some other way (MOVI, e.g.), we can be sneaky.
7255 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7256 SDLoc dl(Op);
7257 unsigned NumElts = VT.getVectorNumElements();
7258 bool isOnlyLowElement = true;
7259 bool usesOnlyOneValue = true;
7260 bool usesOnlyOneConstantValue = true;
7261 bool isConstant = true;
7262 bool AllLanesExtractElt = true;
7263 unsigned NumConstantLanes = 0;
7264 SDValue Value;
7265 SDValue ConstantValue;
7266 for (unsigned i = 0; i < NumElts; ++i) {
7267 SDValue V = Op.getOperand(i);
7268 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7269 AllLanesExtractElt = false;
7270 if (V.isUndef())
7271 continue;
7272 if (i > 0)
7273 isOnlyLowElement = false;
7274 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7275 isConstant = false;
7276
7277 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7278 ++NumConstantLanes;
7279 if (!ConstantValue.getNode())
7280 ConstantValue = V;
7281 else if (ConstantValue != V)
7282 usesOnlyOneConstantValue = false;
7283 }
7284
7285 if (!Value.getNode())
7286 Value = V;
7287 else if (V != Value)
7288 usesOnlyOneValue = false;
7289 }
7290
7291 if (!Value.getNode()) {
7292 LLVM_DEBUG(
7293 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7294 return DAG.getUNDEF(VT);
7295 }
7296
7297 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7298 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7299 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7300 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7301 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7302 "SCALAR_TO_VECTOR node\n");
7303 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7304 }
7305
7306 if (AllLanesExtractElt) {
7307 SDNode *Vector = nullptr;
7308 bool Even = false;
7309 bool Odd = false;
7310 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7311 // the Odd pattern <1,3,5,...>.
7312 for (unsigned i = 0; i < NumElts; ++i) {
7313 SDValue V = Op.getOperand(i);
7314 const SDNode *N = V.getNode();
7315 if (!isa<ConstantSDNode>(N->getOperand(1)))
7316 break;
7317 SDValue N0 = N->getOperand(0);
7318
7319 // All elements are extracted from the same vector.
7320 if (!Vector) {
7321 Vector = N0.getNode();
7322 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7323 // BUILD_VECTOR.
7324 if (VT.getVectorElementType() !=
7325 N0.getValueType().getVectorElementType())
7326 break;
7327 } else if (Vector != N0.getNode()) {
7328 Odd = false;
7329 Even = false;
7330 break;
7331 }
7332
7333 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7334 // indices <1,3,5,...>.
7335 uint64_t Val = N->getConstantOperandVal(1);
7336 if (Val == 2 * i) {
7337 Even = true;
7338 continue;
7339 }
7340 if (Val - 1 == 2 * i) {
7341 Odd = true;
7342 continue;
7343 }
7344
7345 // Something does not match: abort.
7346 Odd = false;
7347 Even = false;
7348 break;
7349 }
7350 if (Even || Odd) {
7351 SDValue LHS =
7352 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7353 DAG.getConstant(0, dl, MVT::i64));
7354 SDValue RHS =
7355 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7356 DAG.getConstant(NumElts, dl, MVT::i64));
7357
7358 if (Even && !Odd)
7359 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7360 RHS);
7361 if (Odd && !Even)
7362 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7363 RHS);
7364 }
7365 }
7366
7367 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7368 // i32 and try again.
7369 if (usesOnlyOneValue) {
7370 if (!isConstant) {
7371 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7372 Value.getValueType() != VT) {
7373 LLVM_DEBUG(
7374 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7375 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7376 }
7377
7378 // This is actually a DUPLANExx operation, which keeps everything vectory.
7379
7380 SDValue Lane = Value.getOperand(1);
7381 Value = Value.getOperand(0);
7382 if (Value.getValueSizeInBits() == 64) {
7383 LLVM_DEBUG(
7384 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7385 "widening it\n");
7386 Value = WidenVector(Value, DAG);
7387 }
7388
7389 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7390 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7391 }
7392
7393 if (VT.getVectorElementType().isFloatingPoint()) {
7394 SmallVector<SDValue, 8> Ops;
7395 EVT EltTy = VT.getVectorElementType();
7396 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7397 "Unsupported floating-point vector type");
7398 LLVM_DEBUG(
7399 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7400 "BITCASTS, and try again\n");
7401 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7402 for (unsigned i = 0; i < NumElts; ++i)
7403 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7404 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7405 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7406 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7407 Val.dump(););
7408 Val = LowerBUILD_VECTOR(Val, DAG);
7409 if (Val.getNode())
7410 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7411 }
7412 }
7413
7414 // If there was only one constant value used and for more than one lane,
7415 // start by splatting that value, then replace the non-constant lanes. This
7416 // is better than the default, which will perform a separate initialization
7417 // for each lane.
7418 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7419 // Firstly, try to materialize the splat constant.
7420 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7421 Val = ConstantBuildVector(Vec, DAG);
7422 if (!Val) {
7423 // Otherwise, materialize the constant and splat it.
7424 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7425 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7426 }
7427
7428 // Now insert the non-constant lanes.
7429 for (unsigned i = 0; i < NumElts; ++i) {
7430 SDValue V = Op.getOperand(i);
7431 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7432 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7433 // Note that type legalization likely mucked about with the VT of the
7434 // source operand, so we may have to convert it here before inserting.
7435 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7436 }
7437 return Val;
7438 }
7439
7440 // This will generate a load from the constant pool.
7441 if (isConstant) {
7442 LLVM_DEBUG(
7443 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7444 "expansion\n");
7445 return SDValue();
7446 }
7447
7448 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7449 if (NumElts >= 4) {
7450 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7451 return shuffle;
7452 }
7453
7454 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7455 // know the default expansion would otherwise fall back on something even
7456 // worse. For a vector with one or two non-undef values, that's
7457 // scalar_to_vector for the elements followed by a shuffle (provided the
7458 // shuffle is valid for the target) and materialization element by element
7459 // on the stack followed by a load for everything else.
7460 if (!isConstant && !usesOnlyOneValue) {
7461 LLVM_DEBUG(
7462 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7463 "of INSERT_VECTOR_ELT\n");
7464
7465 SDValue Vec = DAG.getUNDEF(VT);
7466 SDValue Op0 = Op.getOperand(0);
7467 unsigned i = 0;
7468
7469 // Use SCALAR_TO_VECTOR for lane zero to
7470 // a) Avoid a RMW dependency on the full vector register, and
7471 // b) Allow the register coalescer to fold away the copy if the
7472 // value is already in an S or D register, and we're forced to emit an
7473 // INSERT_SUBREG that we can't fold anywhere.
7474 //
7475 // We also allow types like i8 and i16 which are illegal scalar but legal
7476 // vector element types. After type-legalization the inserted value is
7477 // extended (i32) and it is safe to cast them to the vector type by ignoring
7478 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7479 if (!Op0.isUndef()) {
7480 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7481 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7482 ++i;
7483 }
7484 LLVM_DEBUG(if (i < NumElts) dbgs()
7485 << "Creating nodes for the other vector elements:\n";);
7486 for (; i < NumElts; ++i) {
7487 SDValue V = Op.getOperand(i);
7488 if (V.isUndef())
7489 continue;
7490 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7491 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7492 }
7493 return Vec;
7494 }
7495
7496 LLVM_DEBUG(
7497 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7498 "better alternative\n");
7499 return SDValue();
7500}
7501
7502SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7503 SelectionDAG &DAG) const {
7504 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7505
7506 // Check for non-constant or out of range lane.
7507 EVT VT = Op.getOperand(0).getValueType();
7508 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7509 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7510 return SDValue();
7511
7512
7513 // Insertion/extraction are legal for V128 types.
7514 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7515 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7516 VT == MVT::v8f16)
7517 return Op;
7518
7519 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7520 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7521 return SDValue();
7522
7523 // For V64 types, we perform insertion by expanding the value
7524 // to a V128 type and perform the insertion on that.
7525 SDLoc DL(Op);
7526 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7527 EVT WideTy = WideVec.getValueType();
7528
7529 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7530 Op.getOperand(1), Op.getOperand(2));
7531 // Re-narrow the resultant vector.
7532 return NarrowVector(Node, DAG);
7533}
7534
7535SDValue
7536AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7537 SelectionDAG &DAG) const {
7538 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7539
7540 // Check for non-constant or out of range lane.
7541 EVT VT = Op.getOperand(0).getValueType();
7542 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7543 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7544 return SDValue();
7545
7546
7547 // Insertion/extraction are legal for V128 types.
7548 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7549 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7550 VT == MVT::v8f16)
7551 return Op;
7552
7553 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7554 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7555 return SDValue();
7556
7557 // For V64 types, we perform extraction by expanding the value
7558 // to a V128 type and perform the extraction on that.
7559 SDLoc DL(Op);
7560 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7561 EVT WideTy = WideVec.getValueType();
7562
7563 EVT ExtrTy = WideTy.getVectorElementType();
7564 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7565 ExtrTy = MVT::i32;
7566
7567 // For extractions, we just return the result directly.
7568 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7569 Op.getOperand(1));
7570}
7571
7572SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7573 SelectionDAG &DAG) const {
7574 EVT VT = Op.getOperand(0).getValueType();
7575 SDLoc dl(Op);
7576 // Just in case...
7577 if (!VT.isVector())
7578 return SDValue();
7579
7580 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7581 if (!Cst)
7582 return SDValue();
7583 unsigned Val = Cst->getZExtValue();
7584
7585 unsigned Size = Op.getValueSizeInBits();
7586
7587 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7588 if (Val == 0)
7589 return Op;
7590
7591 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7592 // that directly.
7593 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7594 return Op;
7595
7596 return SDValue();
7597}
7598
7599bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7600 if (VT.getVectorNumElements() == 4 &&
7601 (VT.is128BitVector() || VT.is64BitVector())) {
7602 unsigned PFIndexes[4];
7603 for (unsigned i = 0; i != 4; ++i) {
7604 if (M[i] < 0)
7605 PFIndexes[i] = 8;
7606 else
7607 PFIndexes[i] = M[i];
7608 }
7609
7610 // Compute the index in the perfect shuffle table.
7611 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7612 PFIndexes[2] * 9 + PFIndexes[3];
7613 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7614 unsigned Cost = (PFEntry >> 30);
7615
7616 if (Cost <= 4)
7617 return true;
7618 }
7619
7620 bool DummyBool;
7621 int DummyInt;
7622 unsigned DummyUnsigned;
7623
7624 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7625 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7626 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7627 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7628 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7629 isZIPMask(M, VT, DummyUnsigned) ||
7630 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7631 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7632 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7633 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7634 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7635}
7636
7637/// getVShiftImm - Check if this is a valid build_vector for the immediate
7638/// operand of a vector shift operation, where all the elements of the
7639/// build_vector must have the same constant integer value.
7640static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7641 // Ignore bit_converts.
7642 while (Op.getOpcode() == ISD::BITCAST)
7643 Op = Op.getOperand(0);
7644 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7645 APInt SplatBits, SplatUndef;
7646 unsigned SplatBitSize;
7647 bool HasAnyUndefs;
7648 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7649 HasAnyUndefs, ElementBits) ||
7650 SplatBitSize > ElementBits)
7651 return false;
7652 Cnt = SplatBits.getSExtValue();
7653 return true;
7654}
7655
7656/// isVShiftLImm - Check if this is a valid build_vector for the immediate
7657/// operand of a vector shift left operation. That value must be in the range:
7658/// 0 <= Value < ElementBits for a left shift; or
7659/// 0 <= Value <= ElementBits for a long left shift.
7660static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7661 assert(VT.isVector() && "vector shift count is not a vector type");
7662 int64_t ElementBits = VT.getScalarSizeInBits();
7663 if (!getVShiftImm(Op, ElementBits, Cnt))
7664 return false;
7665 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7666}
7667
7668/// isVShiftRImm - Check if this is a valid build_vector for the immediate
7669/// operand of a vector shift right operation. The value must be in the range:
7670/// 1 <= Value <= ElementBits for a right shift; or
7671static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7672 assert(VT.isVector() && "vector shift count is not a vector type");
7673 int64_t ElementBits = VT.getScalarSizeInBits();
7674 if (!getVShiftImm(Op, ElementBits, Cnt))
7675 return false;
7676 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7677}
7678
7679SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7680 SelectionDAG &DAG) const {
7681 EVT VT = Op.getValueType();
7682 SDLoc DL(Op);
7683 int64_t Cnt;
7684
7685 if (!Op.getOperand(1).getValueType().isVector())
7686 return Op;
7687 unsigned EltSize = VT.getScalarSizeInBits();
7688
7689 switch (Op.getOpcode()) {
7690 default:
7691 llvm_unreachable("unexpected shift opcode");
7692
7693 case ISD::SHL:
7694 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7695 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7696 DAG.getConstant(Cnt, DL, MVT::i32));
7697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7698 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7699 MVT::i32),
7700 Op.getOperand(0), Op.getOperand(1));
7701 case ISD::SRA:
7702 case ISD::SRL:
7703 // Right shift immediate
7704 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7705 unsigned Opc =
7706 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7707 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7708 DAG.getConstant(Cnt, DL, MVT::i32));
7709 }
7710
7711 // Right shift register. Note, there is not a shift right register
7712 // instruction, but the shift left register instruction takes a signed
7713 // value, where negative numbers specify a right shift.
7714 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7715 : Intrinsic::aarch64_neon_ushl;
7716 // negate the shift amount
7717 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7718 SDValue NegShiftLeft =
7719 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7720 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7721 NegShift);
7722 return NegShiftLeft;
7723 }
7724
7725 return SDValue();
7726}
7727
7728static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7729 AArch64CC::CondCode CC, bool NoNans, EVT VT,
7730 const SDLoc &dl, SelectionDAG &DAG) {
7731 EVT SrcVT = LHS.getValueType();
7732 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7733 "function only supposed to emit natural comparisons");
7734
7735 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7736 APInt CnstBits(VT.getSizeInBits(), 0);
7737 APInt UndefBits(VT.getSizeInBits(), 0);
7738 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7739 bool IsZero = IsCnst && (CnstBits == 0);
7740
7741 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7742 switch (CC) {
7743 default:
7744 return SDValue();
7745 case AArch64CC::NE: {
7746 SDValue Fcmeq;
7747 if (IsZero)
7748 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7749 else
7750 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7751 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7752 }
7753 case AArch64CC::EQ:
7754 if (IsZero)
7755 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7756 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7757 case AArch64CC::GE:
7758 if (IsZero)
7759 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7760 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7761 case AArch64CC::GT:
7762 if (IsZero)
7763 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7764 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7765 case AArch64CC::LS:
7766 if (IsZero)
7767 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7768 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7769 case AArch64CC::LT:
7770 if (!NoNans)
7771 return SDValue();
7772 // If we ignore NaNs then we can use to the MI implementation.
7773 LLVM_FALLTHROUGH;
7774 case AArch64CC::MI:
7775 if (IsZero)
7776 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7777 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7778 }
7779 }
7780
7781 switch (CC) {
7782 default:
7783 return SDValue();
7784 case AArch64CC::NE: {
7785 SDValue Cmeq;
7786 if (IsZero)
7787 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7788 else
7789 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7790 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7791 }
7792 case AArch64CC::EQ:
7793 if (IsZero)
7794 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7795 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7796 case AArch64CC::GE:
7797 if (IsZero)
7798 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7799 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7800 case AArch64CC::GT:
7801 if (IsZero)
7802 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7803 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7804 case AArch64CC::LE:
7805 if (IsZero)
7806 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7807 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7808 case AArch64CC::LS:
7809 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7810 case AArch64CC::LO:
7811 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7812 case AArch64CC::LT:
7813 if (IsZero)
7814 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7815 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7816 case AArch64CC::HI:
7817 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7818 case AArch64CC::HS:
7819 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7820 }
7821}
7822
7823SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7824 SelectionDAG &DAG) const {
7825 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7826 SDValue LHS = Op.getOperand(0);
7827 SDValue RHS = Op.getOperand(1);
7828 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7829 SDLoc dl(Op);
7830
7831 if (LHS.getValueType().getVectorElementType().isInteger()) {
7832 assert(LHS.getValueType() == RHS.getValueType());
7833 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7834 SDValue Cmp =
7835 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7836 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7837 }
7838
7839 const bool FullFP16 =
7840 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7841
7842 // Make v4f16 (only) fcmp operations utilise vector instructions
7843 // v8f16 support will be a litle more complicated
7844 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7845 if (LHS.getValueType().getVectorNumElements() == 4) {
7846 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7847 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7848 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7849 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7850 CmpVT = MVT::v4i32;
7851 } else
7852 return SDValue();
7853 }
7854
7855 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7856 LHS.getValueType().getVectorElementType() != MVT::f128);
7857
7858 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7859 // clean. Some of them require two branches to implement.
7860 AArch64CC::CondCode CC1, CC2;
7861 bool ShouldInvert;
7862 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7863
7864 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7865 SDValue Cmp =
7866 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7867 if (!Cmp.getNode())
7868 return SDValue();
7869
7870 if (CC2 != AArch64CC::AL) {
7871 SDValue Cmp2 =
7872 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7873 if (!Cmp2.getNode())
7874 return SDValue();
7875
7876 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7877 }
7878
7879 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7880
7881 if (ShouldInvert)
7882 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7883
7884 return Cmp;
7885}
7886
7887static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7888 SelectionDAG &DAG) {
7889 SDValue VecOp = ScalarOp.getOperand(0);
7890 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7892 DAG.getConstant(0, DL, MVT::i64));
7893}
7894
7895SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7896 SelectionDAG &DAG) const {
7897 SDLoc dl(Op);
7898 switch (Op.getOpcode()) {
7899 case ISD::VECREDUCE_ADD:
7900 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7901 case ISD::VECREDUCE_SMAX:
7902 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7903 case ISD::VECREDUCE_SMIN:
7904 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7905 case ISD::VECREDUCE_UMAX:
7906 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7907 case ISD::VECREDUCE_UMIN:
7908 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7909 case ISD::VECREDUCE_FMAX: {
7910 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7911 return DAG.getNode(
7912 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7913 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7914 Op.getOperand(0));
7915 }
7916 case ISD::VECREDUCE_FMIN: {
7917 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7918 return DAG.getNode(
7919 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7920 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7921 Op.getOperand(0));
7922 }
7923 default:
7924 llvm_unreachable("Unhandled reduction");
7925 }
7926}
7927
7928SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
7929 SelectionDAG &DAG) const {
7930 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7931 if (!Subtarget.hasLSE())
7932 return SDValue();
7933
7934 // LSE has an atomic load-add instruction, but not a load-sub.
7935 SDLoc dl(Op);
7936 MVT VT = Op.getSimpleValueType();
7937 SDValue RHS = Op.getOperand(2);
7938 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7939 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
7940 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
7941 Op.getOperand(0), Op.getOperand(1), RHS,
7942 AN->getMemOperand());
7943}
7944
7945SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
7946 SelectionDAG &DAG) const {
7947 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
7948 if (!Subtarget.hasLSE())
7949 return SDValue();
7950
7951 // LSE has an atomic load-clear instruction, but not a load-and.
7952 SDLoc dl(Op);
7953 MVT VT = Op.getSimpleValueType();
7954 SDValue RHS = Op.getOperand(2);
7955 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
7956 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
7957 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
7958 Op.getOperand(0), Op.getOperand(1), RHS,
7959 AN->getMemOperand());
7960}
7961
7962SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
7963 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
7964 SDLoc dl(Op);
7965 SDValue Callee = DAG.getTargetExternalFunctionSymbol("__chkstk", 0);
7966
7967 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
7968 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
7969 if (Subtarget->hasCustomCallingConv())
7970 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
7971
7972 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
7973 DAG.getConstant(4, dl, MVT::i64));
7974 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
7975 Chain =
7976 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
7977 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
7978 DAG.getRegisterMask(Mask), Chain.getValue(1));
7979 // To match the actual intent better, we should read the output from X15 here
7980 // again (instead of potentially spilling it to the stack), but rereading Size
7981 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
7982 // here.
7983
7984 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
7985 DAG.getConstant(4, dl, MVT::i64));
7986 return Chain;
7987}
7988
7989SDValue
7990AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7991 SelectionDAG &DAG) const {
7992 assert(Subtarget->isTargetWindows() &&
7993 "Only Windows alloca probing supported");
7994 SDLoc dl(Op);
7995 // Get the inputs.
7996 SDNode *Node = Op.getNode();
7997 SDValue Chain = Op.getOperand(0);
7998 SDValue Size = Op.getOperand(1);
7999 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8000 EVT VT = Node->getValueType(0);
8001
8002 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8003 "no-stack-arg-probe")) {
8004 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8005 Chain = SP.getValue(1);
8006 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8007 if (Align)
8008 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8009 DAG.getConstant(-(uint64_t)Align, dl, VT));
8010 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8011 SDValue Ops[2] = {SP, Chain};
8012 return DAG.getMergeValues(Ops, dl);
8013 }
8014
8015 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8016
8017 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8018
8019 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8020 Chain = SP.getValue(1);
8021 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8022 if (Align)
8023 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8024 DAG.getConstant(-(uint64_t)Align, dl, VT));
8025 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8026
8027 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8028 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8029
8030 SDValue Ops[2] = {SP, Chain};
8031 return DAG.getMergeValues(Ops, dl);
8032}
8033
8034/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8035/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8036/// specified in the intrinsic calls.
8037bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8038 const CallInst &I,
8039 MachineFunction &MF,
8040 unsigned Intrinsic) const {
8041 auto &DL = I.getModule()->getDataLayout();
8042 switch (Intrinsic) {
8043 case Intrinsic::aarch64_neon_ld2:
8044 case Intrinsic::aarch64_neon_ld3:
8045 case Intrinsic::aarch64_neon_ld4:
8046 case Intrinsic::aarch64_neon_ld1x2:
8047 case Intrinsic::aarch64_neon_ld1x3:
8048 case Intrinsic::aarch64_neon_ld1x4:
8049 case Intrinsic::aarch64_neon_ld2lane:
8050 case Intrinsic::aarch64_neon_ld3lane:
8051 case Intrinsic::aarch64_neon_ld4lane:
8052 case Intrinsic::aarch64_neon_ld2r:
8053 case Intrinsic::aarch64_neon_ld3r:
8054 case Intrinsic::aarch64_neon_ld4r: {
8055 Info.opc = ISD::INTRINSIC_W_CHAIN;
8056 // Conservatively set memVT to the entire set of vectors loaded.
8057 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8058 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8059 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8060 Info.offset = 0;
8061 Info.align = 0;
8062 // volatile loads with NEON intrinsics not supported
8063 Info.flags = MachineMemOperand::MOLoad;
8064 return true;
8065 }
8066 case Intrinsic::aarch64_neon_st2:
8067 case Intrinsic::aarch64_neon_st3:
8068 case Intrinsic::aarch64_neon_st4:
8069 case Intrinsic::aarch64_neon_st1x2:
8070 case Intrinsic::aarch64_neon_st1x3:
8071 case Intrinsic::aarch64_neon_st1x4:
8072 case Intrinsic::aarch64_neon_st2lane:
8073 case Intrinsic::aarch64_neon_st3lane:
8074 case Intrinsic::aarch64_neon_st4lane: {
8075 Info.opc = ISD::INTRINSIC_VOID;
8076 // Conservatively set memVT to the entire set of vectors stored.
8077 unsigned NumElts = 0;
8078 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8079 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8080 if (!ArgTy->isVectorTy())
8081 break;
8082 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8083 }
8084 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8085 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8086 Info.offset = 0;
8087 Info.align = 0;
8088 // volatile stores with NEON intrinsics not supported
8089 Info.flags = MachineMemOperand::MOStore;
8090 return true;
8091 }
8092 case Intrinsic::aarch64_ldaxr:
8093 case Intrinsic::aarch64_ldxr: {
8094 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8095 Info.opc = ISD::INTRINSIC_W_CHAIN;
8096 Info.memVT = MVT::getVT(PtrTy->getElementType());
8097 Info.ptrVal = I.getArgOperand(0);
8098 Info.offset = 0;
8099 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
8100 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8101 return true;
8102 }
8103 case Intrinsic::aarch64_stlxr:
8104 case Intrinsic::aarch64_stxr: {
8105 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8106 Info.opc = ISD::INTRINSIC_W_CHAIN;
8107 Info.memVT = MVT::getVT(PtrTy->getElementType());
8108 Info.ptrVal = I.getArgOperand(1);
8109 Info.offset = 0;
8110 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
8111 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8112 return true;
8113 }
8114 case Intrinsic::aarch64_ldaxp:
8115 case Intrinsic::aarch64_ldxp:
8116 Info.opc = ISD::INTRINSIC_W_CHAIN;
8117 Info.memVT = MVT::i128;
8118 Info.ptrVal = I.getArgOperand(0);
8119 Info.offset = 0;
8120 Info.align = 16;
8121 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8122 return true;
8123 case Intrinsic::aarch64_stlxp:
8124 case Intrinsic::aarch64_stxp:
8125 Info.opc = ISD::INTRINSIC_W_CHAIN;
8126 Info.memVT = MVT::i128;
8127 Info.ptrVal = I.getArgOperand(2);
8128 Info.offset = 0;
8129 Info.align = 16;
8130 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8131 return true;
8132 default:
8133 break;
8134 }
8135
8136 return false;
8137}
8138
8139bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8140 ISD::LoadExtType ExtTy,
8141 EVT NewVT) const {
8142 // TODO: This may be worth removing. Check regression tests for diffs.
8143 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8144 return false;
8145
8146 // If we're reducing the load width in order to avoid having to use an extra
8147 // instruction to do extension then it's probably a good idea.
8148 if (ExtTy != ISD::NON_EXTLOAD)
8149 return true;
8150 // Don't reduce load width if it would prevent us from combining a shift into
8151 // the offset.
8152 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8153 assert(Mem);
8154 const SDValue &Base = Mem->getBasePtr();
8155 if (Base.getOpcode() == ISD::ADD &&
8156 Base.getOperand(1).getOpcode() == ISD::SHL &&
8157 Base.getOperand(1).hasOneUse() &&
8158 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8159 // The shift can be combined if it matches the size of the value being
8160 // loaded (and so reducing the width would make it not match).
8161 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8162 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8163 if (ShiftAmount == Log2_32(LoadBytes))
8164 return false;
8165 }
8166 // We have no reason to disallow reducing the load width, so allow it.
8167 return true;
8168}
8169
8170// Truncations from 64-bit GPR to 32-bit GPR is free.
8171bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8172 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8173 return false;
8174 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8175 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8176 return NumBits1 > NumBits2;
8177}
8178bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8179 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8180 return false;
8181 unsigned NumBits1 = VT1.getSizeInBits();
8182 unsigned NumBits2 = VT2.getSizeInBits();
8183 return NumBits1 > NumBits2;
8184}
8185
8186/// Check if it is profitable to hoist instruction in then/else to if.
8187/// Not profitable if I and it's user can form a FMA instruction
8188/// because we prefer FMSUB/FMADD.
8189bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8190 if (I->getOpcode() != Instruction::FMul)
8191 return true;
8192
8193 if (!I->hasOneUse())
8194 return true;
8195
8196 Instruction *User = I->user_back();
8197
8198 if (User &&
8199 !(User->getOpcode() == Instruction::FSub ||
8200 User->getOpcode() == Instruction::FAdd))
8201 return true;
8202
8203 const TargetOptions &Options = getTargetMachine().Options;
8204 const DataLayout &DL = I->getModule()->getDataLayout();
8205 EVT VT = getValueType(DL, User->getOperand(0)->getType());
8206
8207 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8208 isOperationLegalOrCustom(ISD::FMA, VT) &&
8209 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8210 Options.UnsafeFPMath));
8211}
8212
8213// All 32-bit GPR operations implicitly zero the high-half of the corresponding
8214// 64-bit GPR.
8215bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8216 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8217 return false;
8218 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8219 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8220 return NumBits1 == 32 && NumBits2 == 64;
8221}
8222bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8223 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8224 return false;
8225 unsigned NumBits1 = VT1.getSizeInBits();
8226 unsigned NumBits2 = VT2.getSizeInBits();
8227 return NumBits1 == 32 && NumBits2 == 64;
8228}
8229
8230bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8231 EVT VT1 = Val.getValueType();
8232 if (isZExtFree(VT1, VT2)) {
8233 return true;
8234 }
8235
8236 if (Val.getOpcode() != ISD::LOAD)
8237 return false;
8238
8239 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8240 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8241 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8242 VT1.getSizeInBits() <= 32);
8243}
8244
8245bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8246 if (isa<FPExtInst>(Ext))
8247 return false;
8248
8249 // Vector types are not free.
8250 if (Ext->getType()->isVectorTy())
8251 return false;
8252
8253 for (const Use &U : Ext->uses()) {
8254 // The extension is free if we can fold it with a left shift in an
8255 // addressing mode or an arithmetic operation: add, sub, and cmp.
8256
8257 // Is there a shift?
8258 const Instruction *Instr = cast<Instruction>(U.getUser());
8259
8260 // Is this a constant shift?
8261 switch (Instr->getOpcode()) {
8262 case Instruction::Shl:
8263 if (!isa<ConstantInt>(Instr->getOperand(1)))
8264 return false;
8265 break;
8266 case Instruction::GetElementPtr: {
8267 gep_type_iterator GTI = gep_type_begin(Instr);
8268 auto &DL = Ext->getModule()->getDataLayout();
8269 std::advance(GTI, U.getOperandNo()-1);
8270 Type *IdxTy = GTI.getIndexedType();
8271 // This extension will end up with a shift because of the scaling factor.
8272 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8273 // Get the shift amount based on the scaling factor:
8274 // log2(sizeof(IdxTy)) - log2(8).
8275 uint64_t ShiftAmt =
8276 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
8277 // Is the constant foldable in the shift of the addressing mode?
8278 // I.e., shift amount is between 1 and 4 inclusive.
8279 if (ShiftAmt == 0 || ShiftAmt > 4)
8280 return false;
8281 break;
8282 }
8283 case Instruction::Trunc:
8284 // Check if this is a noop.
8285 // trunc(sext ty1 to ty2) to ty1.
8286 if (Instr->getType() == Ext->getOperand(0)->getType())
8287 continue;
8288 LLVM_FALLTHROUGH;
8289 default:
8290 return false;
8291 }
8292
8293 // At this point we can use the bfm family, so this extension is free
8294 // for that use.
8295 }
8296 return true;
8297}
8298
8299/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8300/// or upper half of the vector elements.
8301static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8302 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8303 auto *FullVT = cast<VectorType>(FullV->getType());
8304 auto *HalfVT = cast<VectorType>(HalfV->getType());
8305 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8306 };
8307
8308 auto extractHalf = [](Value *FullV, Value *HalfV) {
8309 auto *FullVT = cast<VectorType>(FullV->getType());
8310 auto *HalfVT = cast<VectorType>(HalfV->getType());
8311 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8312 };
8313
8314 Constant *M1, *M2;
8315 Value *S1Op1, *S2Op1;
8316 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8317 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8318 return false;
8319
8320 // Check that the operands are half as wide as the result and we extract
8321 // half of the elements of the input vectors.
8322 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8323 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8324 return false;
8325
8326 // Check the mask extracts either the lower or upper half of vector
8327 // elements.
8328 int M1Start = -1;
8329 int M2Start = -1;
8330 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8331 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8332 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8333 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8334 return false;
8335
8336 return true;
8337}
8338
8339/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8340/// of the vector elements.
8341static bool areExtractExts(Value *Ext1, Value *Ext2) {
8342 auto areExtDoubled = [](Instruction *Ext) {
8343 return Ext->getType()->getScalarSizeInBits() ==
8344 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8345 };
8346
8347 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8348 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8349 !areExtDoubled(cast<Instruction>(Ext1)) ||
8350 !areExtDoubled(cast<Instruction>(Ext2)))
8351 return false;
8352
8353 return true;
8354}
8355
8356/// Check if sinking \p I's operands to I's basic block is profitable, because
8357/// the operands can be folded into a target instruction, e.g.
8358/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8359bool AArch64TargetLowering::shouldSinkOperands(
8360 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8361 if (!I->getType()->isVectorTy())
8362 return false;
8363
8364 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8365 switch (II->getIntrinsicID()) {
8366 case Intrinsic::aarch64_neon_umull:
8367 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8368 return false;
8369 Ops.push_back(&II->getOperandUse(0));
8370 Ops.push_back(&II->getOperandUse(1));
8371 return true;
8372 default:
8373 return false;
8374 }
8375 }
8376
8377 switch (I->getOpcode()) {
8378 case Instruction::Sub:
8379 case Instruction::Add: {
8380 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8381 return false;
8382
8383 // If the exts' operands extract either the lower or upper elements, we
8384 // can sink them too.
8385 auto Ext1 = cast<Instruction>(I->getOperand(0));
8386 auto Ext2 = cast<Instruction>(I->getOperand(1));
8387 if (areExtractShuffleVectors(Ext1, Ext2)) {
8388 Ops.push_back(&Ext1->getOperandUse(0));
8389 Ops.push_back(&Ext2->getOperandUse(0));
8390 }
8391
8392 Ops.push_back(&I->getOperandUse(0));
8393 Ops.push_back(&I->getOperandUse(1));
8394
8395 return true;
8396 }
8397 default:
8398 return false;
8399 }
8400 return false;
8401}
8402
8403bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8404 unsigned &RequiredAligment) const {
8405 if (!LoadedType.isSimple() ||
8406 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8407 return false;
8408 // Cyclone supports unaligned accesses.
8409 RequiredAligment = 0;
8410 unsigned NumBits = LoadedType.getSizeInBits();
8411 return NumBits == 32 || NumBits == 64;
8412}
8413
8414/// A helper function for determining the number of interleaved accesses we
8415/// will generate when lowering accesses of the given type.
8416unsigned
8417AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8418 const DataLayout &DL) const {
8419 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8420}
8421
8422MachineMemOperand::Flags
8423AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8424 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8425 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8426 return MOStridedAccess;
8427 return MachineMemOperand::MONone;
8428}
8429
8430bool AArch64TargetLowering::isLegalInterleavedAccessType(
8431 VectorType *VecTy, const DataLayout &DL) const {
8432
8433 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8434 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8435
8436 // Ensure the number of vector elements is greater than 1.
8437 if (VecTy->getNumElements() < 2)
8438 return false;
8439
8440 // Ensure the element type is legal.
8441 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8442 return false;
8443
8444 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8445 // 128 will be split into multiple interleaved accesses.
8446 return VecSize == 64 || VecSize % 128 == 0;
8447}
8448
8449/// Lower an interleaved load into a ldN intrinsic.
8450///
8451/// E.g. Lower an interleaved load (Factor = 2):
8452/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8453/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8454/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8455///
8456/// Into:
8457/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8458/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8459/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8460bool AArch64TargetLowering::lowerInterleavedLoad(
8461 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8462 ArrayRef<unsigned> Indices, unsigned Factor) const {
8463 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8464 "Invalid interleave factor");
8465 assert(!Shuffles.empty() && "Empty shufflevector input");
8466 assert(Shuffles.size() == Indices.size() &&
8467 "Unmatched number of shufflevectors and indices");
8468
8469 const DataLayout &DL = LI->getModule()->getDataLayout();
8470
8471 VectorType *VecTy = Shuffles[0]->getType();
8472
8473 // Skip if we do not have NEON and skip illegal vector types. We can
8474 // "legalize" wide vector types into multiple interleaved accesses as long as
8475 // the vector types are divisible by 128.
8476 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8477 return false;
8478
8479 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8480
8481 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8482 // load integer vectors first and then convert to pointer vectors.
8483 Type *EltTy = VecTy->getVectorElementType();
8484 if (EltTy->isPointerTy())
8485 VecTy =
8486 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8487
8488 IRBuilder<> Builder(LI);
8489
8490 // The base address of the load.
8491 Value *BaseAddr = LI->getPointerOperand();
8492
8493 if (NumLoads > 1) {
8494 // If we're going to generate more than one load, reset the sub-vector type
8495 // to something legal.
8496 VecTy = VectorType::get(VecTy->getVectorElementType(),
8497 VecTy->getVectorNumElements() / NumLoads);
8498
8499 // We will compute the pointer operand of each load from the original base
8500 // address using GEPs. Cast the base address to a pointer to the scalar
8501 // element type.
8502 BaseAddr = Builder.CreateBitCast(
8503 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8504 LI->getPointerAddressSpace()));
8505 }
8506
8507 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8508 Type *Tys[2] = {VecTy, PtrTy};
8509 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8510 Intrinsic::aarch64_neon_ld3,
8511 Intrinsic::aarch64_neon_ld4};
8512 Function *LdNFunc =
8513 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8514
8515 // Holds sub-vectors extracted from the load intrinsic return values. The
8516 // sub-vectors are associated with the shufflevector instructions they will
8517 // replace.
8518 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8519
8520 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8521
8522 // If we're generating more than one load, compute the base address of
8523 // subsequent loads as an offset from the previous.
8524 if (LoadCount > 0)
8525 BaseAddr =
8526 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8527 VecTy->getVectorNumElements() * Factor);
8528
8529 CallInst *LdN = Builder.CreateCall(
8530 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8531
8532 // Extract and store the sub-vectors returned by the load intrinsic.
8533 for (unsigned i = 0; i < Shuffles.size(); i++) {
8534 ShuffleVectorInst *SVI = Shuffles[i];
8535 unsigned Index = Indices[i];
8536
8537 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8538
8539 // Convert the integer vector to pointer vector if the element is pointer.
8540 if (EltTy->isPointerTy())
8541 SubVec = Builder.CreateIntToPtr(
8542 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8543 VecTy->getVectorNumElements()));
8544 SubVecs[SVI].push_back(SubVec);
8545 }
8546 }
8547
8548 // Replace uses of the shufflevector instructions with the sub-vectors
8549 // returned by the load intrinsic. If a shufflevector instruction is
8550 // associated with more than one sub-vector, those sub-vectors will be
8551 // concatenated into a single wide vector.
8552 for (ShuffleVectorInst *SVI : Shuffles) {
8553 auto &SubVec = SubVecs[SVI];
8554 auto *WideVec =
8555 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8556 SVI->replaceAllUsesWith(WideVec);
8557 }
8558
8559 return true;
8560}
8561
8562/// Lower an interleaved store into a stN intrinsic.
8563///
8564/// E.g. Lower an interleaved store (Factor = 3):
8565/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8566/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8567/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8568///
8569/// Into:
8570/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8571/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8572/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8573/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8574///
8575/// Note that the new shufflevectors will be removed and we'll only generate one
8576/// st3 instruction in CodeGen.
8577///
8578/// Example for a more general valid mask (Factor 3). Lower:
8579/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8580/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8581/// store <12 x i32> %i.vec, <12 x i32>* %ptr
8582///
8583/// Into:
8584/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8585/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8586/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8587/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8588bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8589 ShuffleVectorInst *SVI,
8590 unsigned Factor) const {
8591 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8592 "Invalid interleave factor");
8593
8594 VectorType *VecTy = SVI->getType();
8595 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8596 "Invalid interleaved store");
8597
8598 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8599 Type *EltTy = VecTy->getVectorElementType();
8600 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8601
8602 const DataLayout &DL = SI->getModule()->getDataLayout();
8603
8604 // Skip if we do not have NEON and skip illegal vector types. We can
8605 // "legalize" wide vector types into multiple interleaved accesses as long as
8606 // the vector types are divisible by 128.
8607 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8608 return false;
8609
8610 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8611
8612 Value *Op0 = SVI->getOperand(0);
8613 Value *Op1 = SVI->getOperand(1);
8614 IRBuilder<> Builder(SI);
8615
8616 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8617 // vectors to integer vectors.
8618 if (EltTy->isPointerTy()) {
8619 Type *IntTy = DL.getIntPtrType(EltTy);
8620 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8621
8622 // Convert to the corresponding integer vector.
8623 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8624 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8625 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8626
8627 SubVecTy = VectorType::get(IntTy, LaneLen);
8628 }
8629
8630 // The base address of the store.
8631 Value *BaseAddr = SI->getPointerOperand();
8632
8633 if (NumStores > 1) {
8634 // If we're going to generate more than one store, reset the lane length
8635 // and sub-vector type to something legal.
8636 LaneLen /= NumStores;
8637 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8638
8639 // We will compute the pointer operand of each store from the original base
8640 // address using GEPs. Cast the base address to a pointer to the scalar
8641 // element type.
8642 BaseAddr = Builder.CreateBitCast(
8643 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8644 SI->getPointerAddressSpace()));
8645 }
8646
8647 auto Mask = SVI->getShuffleMask();
8648
8649 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8650 Type *Tys[2] = {SubVecTy, PtrTy};
8651 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8652 Intrinsic::aarch64_neon_st3,
8653 Intrinsic::aarch64_neon_st4};
8654 Function *StNFunc =
8655 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8656
8657 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8658
8659 SmallVector<Value *, 5> Ops;
8660
8661 // Split the shufflevector operands into sub vectors for the new stN call.
8662 for (unsigned i = 0; i < Factor; i++) {
8663 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8664 if (Mask[IdxI] >= 0) {
8665 Ops.push_back(Builder.CreateShuffleVector(
8666 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8667 } else {
8668 unsigned StartMask = 0;
8669 for (unsigned j = 1; j < LaneLen; j++) {
8670 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8671 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8672 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8673 break;
8674 }
8675 }
8676 // Note: Filling undef gaps with random elements is ok, since
8677 // those elements were being written anyway (with undefs).
8678 // In the case of all undefs we're defaulting to using elems from 0
8679 // Note: StartMask cannot be negative, it's checked in
8680 // isReInterleaveMask
8681 Ops.push_back(Builder.CreateShuffleVector(
8682 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8683 }
8684 }
8685
8686 // If we generating more than one store, we compute the base address of
8687 // subsequent stores as an offset from the previous.
8688 if (StoreCount > 0)
8689 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8690 BaseAddr, LaneLen * Factor);
8691
8692 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8693 Builder.CreateCall(StNFunc, Ops);
8694 }
8695 return true;
8696}
8697
8698static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8699 unsigned AlignCheck) {
8700 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8701 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8702}
8703
8704EVT AArch64TargetLowering::getOptimalMemOpType(
8705 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8706 bool ZeroMemset, bool MemcpyStrSrc,
8707 const AttributeList &FuncAttributes) const {
8708 bool CanImplicitFloat =
8709 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8710 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8711 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8712 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8713 // taken one instruction to materialize the v2i64 zero and one store (with
8714 // restrictive addressing mode). Just do i64 stores.
8715 bool IsSmallMemset = IsMemset && Size < 32;
8716 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8717 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8718 return true;
8719 bool Fast;
8720 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8721 &Fast) &&
8722 Fast;
8723 };
8724
8725 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8726 AlignmentIsAcceptable(MVT::v2i64, 16))
8727 return MVT::v2i64;
8728 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8729 return MVT::f128;
8730 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8731 return MVT::i64;
8732 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8733 return MVT::i32;
8734 return MVT::Other;
8735}
8736
8737// 12-bit optionally shifted immediates are legal for adds.
8738bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
8739 if (Immed == std::numeric_limits<int64_t>::min()) {
8740 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8741 << ": avoid UB for INT64_MIN\n");
8742 return false;
8743 }
8744 // Same encoding for add/sub, just flip the sign.
8745 Immed = std::abs(Immed);
8746 bool IsLegal = ((Immed >> 12) == 0 ||
8747 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8748 LLVM_DEBUG(dbgs() << "Is " << Immed
8749 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
8750 return IsLegal;
8751}
8752
8753// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8754// immediates is the same as for an add or a sub.
8755bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
8756 return isLegalAddImmediate(Immed);
8757}
8758
8759/// isLegalAddressingMode - Return true if the addressing mode represented
8760/// by AM is legal for this target, for a load/store of the specified type.
8761bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8762 const AddrMode &AM, Type *Ty,
8763 unsigned AS, Instruction *I) const {
8764 // AArch64 has five basic addressing modes:
8765 // reg
8766 // reg + 9-bit signed offset
8767 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8768 // reg1 + reg2
8769 // reg + SIZE_IN_BYTES * reg
8770
8771 // No global is ever allowed as a base.
8772 if (AM.BaseGV)
8773 return false;
8774
8775 // No reg+reg+imm addressing.
8776 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8777 return false;
8778
8779 // check reg + imm case:
8780 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8781 uint64_t NumBytes = 0;
8782 if (Ty->isSized()) {
8783 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
8784 NumBytes = NumBits / 8;
8785 if (!isPowerOf2_64(NumBits))
8786 NumBytes = 0;
8787 }
8788
8789 if (!AM.Scale) {
8790 int64_t Offset = AM.BaseOffs;
8791
8792 // 9-bit signed offset
8793 if (isInt<9>(Offset))
8794 return true;
8795
8796 // 12-bit unsigned offset
8797 unsigned shift = Log2_64(NumBytes);
8798 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8799 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8800 (Offset >> shift) << shift == Offset)
8801 return true;
8802 return false;
8803 }
8804
8805 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8806
8807 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8808}
8809
8810bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8811 // Consider splitting large offset of struct or array.
8812 return true;
8813}
8814
8815int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8816 const AddrMode &AM, Type *Ty,
8817 unsigned AS) const {
8818 // Scaling factors are not free at all.
8819 // Operands | Rt Latency
8820 // -------------------------------------------
8821 // Rt, [Xn, Xm] | 4
8822 // -------------------------------------------
8823 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8824 // Rt, [Xn, Wm, <extend> #imm] |
8825 if (isLegalAddressingMode(DL, AM, Ty, AS))
8826 // Scale represents reg2 * scale, thus account for 1 if
8827 // it is not equal to 0 or 1.
8828 return AM.Scale != 0 && AM.Scale != 1;
8829 return -1;
8830}
8831
8832bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8833 VT = VT.getScalarType();
8834
8835 if (!VT.isSimple())
8836 return false;
8837
8838 switch (VT.getSimpleVT().SimpleTy) {
8839 case MVT::f32:
8840 case MVT::f64:
8841 return true;
8842 default:
8843 break;
8844 }
8845
8846 return false;
8847}
8848
8849const MCPhysReg *
8850AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8851 // LR is a callee-save register, but we must treat it as clobbered by any call
8852 // site. Hence we include LR in the scratch registers, which are in turn added
8853 // as implicit-defs for stackmaps and patchpoints.
8854 static const MCPhysReg ScratchRegs[] = {
8855 AArch64::X16, AArch64::X17, AArch64::LR, 0
8856 };
8857 return ScratchRegs;
8858}
8859
8860bool
8861AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8862 CombineLevel Level) const {
8863 N = N->getOperand(0).getNode();
8864 EVT VT = N->getValueType(0);
8865 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8866 // it with shift to let it be lowered to UBFX.
8867 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8868 isa<ConstantSDNode>(N->getOperand(1))) {
8869 uint64_t TruncMask = N->getConstantOperandVal(1);
8870 if (isMask_64(TruncMask) &&
8871 N->getOperand(0).getOpcode() == ISD::SRL &&
8872 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8873 return false;
8874 }
8875 return true;
8876}
8877
8878bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8879 Type *Ty) const {
8880 assert(Ty->isIntegerTy());
8881
8882 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8883 if (BitSize == 0)
8884 return false;
8885
8886 int64_t Val = Imm.getSExtValue();
8887 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8888 return true;
8889
8890 if ((int64_t)Val < 0)
8891 Val = ~Val;
8892 if (BitSize == 32)
8893 Val &= (1LL << 32) - 1;
8894
8895 unsigned LZ = countLeadingZeros((uint64_t)Val);
8896 unsigned Shift = (63 - LZ) / 16;
8897 // MOVZ is free so return true for one or fewer MOVK.
8898 return Shift < 3;
8899}
8900
8901bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
8902 unsigned Index) const {
8903 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
8904 return false;
8905
8906 return (Index == 0 || Index == ResVT.getVectorNumElements());
8907}
8908
8909/// Turn vector tests of the signbit in the form of:
8910/// xor (sra X, elt_size(X)-1), -1
8911/// into:
8912/// cmge X, X, #0
8913static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8914 const AArch64Subtarget *Subtarget) {
8915 EVT VT = N->getValueType(0);
8916 if (!Subtarget->hasNEON() || !VT.isVector())
8917 return SDValue();
8918
8919 // There must be a shift right algebraic before the xor, and the xor must be a
8920 // 'not' operation.
8921 SDValue Shift = N->getOperand(0);
8922 SDValue Ones = N->getOperand(1);
8923 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8924 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8925 return SDValue();
8926
8927 // The shift should be smearing the sign bit across each vector element.
8928 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8929 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8930 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8931 return SDValue();
8932
8933 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8934}
8935
8936// Generate SUBS and CSEL for integer abs.
8937static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8938 EVT VT = N->getValueType(0);
8939
8940 SDValue N0 = N->getOperand(0);
8941 SDValue N1 = N->getOperand(1);
8942 SDLoc DL(N);
8943
8944 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8945 // and change it to SUB and CSEL.
8946 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8947 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8948 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8949 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8950 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
8951 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
8952 N0.getOperand(0));
8953 // Generate SUBS & CSEL.
8954 SDValue Cmp =
8955 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
8956 N0.getOperand(0), DAG.getConstant(0, DL, VT));
8957 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8958 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8959 SDValue(Cmp.getNode(), 1));
8960 }
8961 return SDValue();
8962}
8963
8964static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8965 TargetLowering::DAGCombinerInfo &DCI,
8966 const AArch64Subtarget *Subtarget) {
8967 if (DCI.isBeforeLegalizeOps())
8968 return SDValue();
8969
8970 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8971 return Cmp;
8972
8973 return performIntegerAbsCombine(N, DAG);
8974}
8975
8976SDValue
8977AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8978 SelectionDAG &DAG,
8979 SmallVectorImpl<SDNode *> &Created) const {
8980 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
8981 if (isIntDivCheap(N->getValueType(0), Attr))
8982 return SDValue(N,0); // Lower SDIV as SDIV
8983
8984 // fold (sdiv X, pow2)
8985 EVT VT = N->getValueType(0);
8986 if ((VT != MVT::i32 && VT != MVT::i64) ||
8987 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8988 return SDValue();
8989
8990 SDLoc DL(N);
8991 SDValue N0 = N->getOperand(0);
8992 unsigned Lg2 = Divisor.countTrailingZeros();
8993 SDValue Zero = DAG.getConstant(0, DL, VT);
8994 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8995
8996 // Add (N0 < 0) ? Pow2 - 1 : 0;
8997 SDValue CCVal;
8998 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8999 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9000 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9001
9002 Created.push_back(Cmp.getNode());
9003 Created.push_back(Add.getNode());
9004 Created.push_back(CSel.getNode());
9005
9006 // Divide by pow2.
9007 SDValue SRA =
9008 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9009
9010 // If we're dividing by a positive value, we're done. Otherwise, we must
9011 // negate the result.
9012 if (Divisor.isNonNegative())
9013 return SRA;
9014
9015 Created.push_back(SRA.getNode());
9016 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9017}
9018
9019static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9020 TargetLowering::DAGCombinerInfo &DCI,
9021 const AArch64Subtarget *Subtarget) {
9022 if (DCI.isBeforeLegalizeOps())
9023 return SDValue();
9024
9025 // The below optimizations require a constant RHS.
9026 if (!isa<ConstantSDNode>(N->getOperand(1)))
9027 return SDValue();
9028
9029 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9030 const APInt &ConstValue = C->getAPIntValue();
9031
9032 // Multiplication of a power of two plus/minus one can be done more
9033 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9034 // future CPUs have a cheaper MADD instruction, this may need to be
9035 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9036 // 64-bit is 5 cycles, so this is always a win.
9037 // More aggressively, some multiplications N0 * C can be lowered to
9038 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9039 // e.g. 6=3*2=(2+1)*2.
9040 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9041 // which equals to (1+2)*16-(1+2).
9042 SDValue N0 = N->getOperand(0);
9043 // TrailingZeroes is used to test if the mul can be lowered to
9044 // shift+add+shift.
9045 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9046 if (TrailingZeroes) {
9047 // Conservatively do not lower to shift+add+shift if the mul might be
9048 // folded into smul or umul.
9049 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9050 isZeroExtended(N0.getNode(), DAG)))
9051 return SDValue();
9052 // Conservatively do not lower to shift+add+shift if the mul might be
9053 // folded into madd or msub.
9054 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9055 N->use_begin()->getOpcode() == ISD::SUB))
9056 return SDValue();
9057 }
9058 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9059 // and shift+add+shift.
9060 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9061
9062 unsigned ShiftAmt, AddSubOpc;
9063 // Is the shifted value the LHS operand of the add/sub?
9064 bool ShiftValUseIsN0 = true;
9065 // Do we need to negate the result?
9066 bool NegateResult = false;
9067
9068 if (ConstValue.isNonNegative()) {
9069 // (mul x, 2^N + 1) => (add (shl x, N), x)
9070 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9071 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9072 APInt SCVMinus1 = ShiftedConstValue - 1;
9073 APInt CVPlus1 = ConstValue + 1;
9074 if (SCVMinus1.isPowerOf2()) {
9075 ShiftAmt = SCVMinus1.logBase2();
9076 AddSubOpc = ISD::ADD;
9077 } else if (CVPlus1.isPowerOf2()) {
9078 ShiftAmt = CVPlus1.logBase2();
9079 AddSubOpc = ISD::SUB;
9080 } else
9081 return SDValue();
9082 } else {
9083 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9084 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9085 APInt CVNegPlus1 = -ConstValue + 1;
9086 APInt CVNegMinus1 = -ConstValue - 1;
9087 if (CVNegPlus1.isPowerOf2()) {
9088 ShiftAmt = CVNegPlus1.logBase2();
9089 AddSubOpc = ISD::SUB;
9090 ShiftValUseIsN0 = false;
9091 } else if (CVNegMinus1.isPowerOf2()) {
9092 ShiftAmt = CVNegMinus1.logBase2();
9093 AddSubOpc = ISD::ADD;
9094 NegateResult = true;
9095 } else
9096 return SDValue();
9097 }
9098
9099 SDLoc DL(N);
9100 EVT VT = N->getValueType(0);
9101 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9102 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9103
9104 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9105 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9106 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9107 assert(!(NegateResult && TrailingZeroes) &&
9108 "NegateResult and TrailingZeroes cannot both be true for now.");
9109 // Negate the result.
9110 if (NegateResult)
9111 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9112 // Shift the result.
9113 if (TrailingZeroes)
9114 return DAG.getNode(ISD::SHL, DL, VT, Res,
9115 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9116 return Res;
9117}
9118
9119static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9120 SelectionDAG &DAG) {
9121 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9122 // optimize away operation when it's from a constant.
9123 //
9124 // The general transformation is:
9125 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9126 // AND(VECTOR_CMP(x,y), constant2)
9127 // constant2 = UNARYOP(constant)
9128
9129 // Early exit if this isn't a vector operation, the operand of the
9130 // unary operation isn't a bitwise AND, or if the sizes of the operations
9131 // aren't the same.
9132 EVT VT = N->getValueType(0);
9133 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9134 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9135 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9136 return SDValue();
9137
9138 // Now check that the other operand of the AND is a constant. We could
9139 // make the transformation for non-constant splats as well, but it's unclear
9140 // that would be a benefit as it would not eliminate any operations, just
9141 // perform one more step in scalar code before moving to the vector unit.
9142 if (BuildVectorSDNode *BV =
9143 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9144 // Bail out if the vector isn't a constant.
9145 if (!BV->isConstant())
9146 return SDValue();
9147
9148 // Everything checks out. Build up the new and improved node.
9149 SDLoc DL(N);
9150 EVT IntVT = BV->getValueType(0);
9151 // Create a new constant of the appropriate type for the transformed
9152 // DAG.
9153 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9154 // The AND node needs bitcasts to/from an integer vector type around it.
9155 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9156 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9157 N->getOperand(0)->getOperand(0), MaskConst);
9158 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9159 return Res;
9160 }
9161
9162 return SDValue();
9163}
9164
9165static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9166 const AArch64Subtarget *Subtarget) {
9167 // First try to optimize away the conversion when it's conditionally from
9168 // a constant. Vectors only.
9169 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9170 return Res;
9171
9172 EVT VT = N->getValueType(0);
9173 if (VT != MVT::f32 && VT != MVT::f64)
9174 return SDValue();
9175
9176 // Only optimize when the source and destination types have the same width.
9177 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9178 return SDValue();
9179
9180 // If the result of an integer load is only used by an integer-to-float
9181 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9182 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9183 SDValue N0 = N->getOperand(0);
9184 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9185 // Do not change the width of a volatile load.
9186 !cast<LoadSDNode>(N0)->isVolatile()) {
9187 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9188 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9189 LN0->getPointerInfo(), LN0->getAlignment(),
9190 LN0->getMemOperand()->getFlags());
9191
9192 // Make sure successors of the original load stay after it by updating them
9193 // to use the new Chain.
9194 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9195
9196 unsigned Opcode =
9197 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9198 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9199 }
9200
9201 return SDValue();
9202}
9203
9204/// Fold a floating-point multiply by power of two into floating-point to
9205/// fixed-point conversion.
9206static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9207 TargetLowering::DAGCombinerInfo &DCI,
9208 const AArch64Subtarget *Subtarget) {
9209 if (!Subtarget->hasNEON())
9210 return SDValue();
9211
9212 if (!N->getValueType(0).isSimple())
9213 return SDValue();
9214
9215 SDValue Op = N->getOperand(0);
9216 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9217 Op.getOpcode() != ISD::FMUL)
9218 return SDValue();
9219
9220 SDValue ConstVec = Op->getOperand(1);
9221 if (!isa<BuildVectorSDNode>(ConstVec))
9222 return SDValue();
9223
9224 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9225 uint32_t FloatBits = FloatTy.getSizeInBits();
9226 if (FloatBits != 32 && FloatBits != 64)
9227 return SDValue();
9228
9229 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9230 uint32_t IntBits = IntTy.getSizeInBits();
9231 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9232 return SDValue();
9233
9234 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9235 if (IntBits > FloatBits)
9236 return SDValue();
9237
9238 BitVector UndefElements;
9239 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9240 int32_t Bits = IntBits == 64 ? 64 : 32;
9241 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9242 if (C == -1 || C == 0 || C > Bits)
9243 return SDValue();
9244
9245 MVT ResTy;
9246 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9247 switch (NumLanes) {
9248 default:
9249 return SDValue();
9250 case 2:
9251 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9252 break;
9253 case 4:
9254 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9255 break;
9256 }
9257
9258 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9259 return SDValue();
9260
9261 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9262 "Illegal vector type after legalization");
9263
9264 SDLoc DL(N);
9265 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9266 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9267 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9268 SDValue FixConv =
9269 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9270 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9271 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9272 // We can handle smaller integers by generating an extra trunc.
9273 if (IntBits < FloatBits)
9274 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9275
9276 return FixConv;
9277}
9278
9279/// Fold a floating-point divide by power of two into fixed-point to
9280/// floating-point conversion.
9281static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9282 TargetLowering::DAGCombinerInfo &DCI,
9283 const AArch64Subtarget *Subtarget) {
9284 if (!Subtarget->hasNEON())
9285 return SDValue();
9286
9287 SDValue Op = N->getOperand(0);
9288 unsigned Opc = Op->getOpcode();
9289 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9290 !Op.getOperand(0).getValueType().isSimple() ||
9291 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9292 return SDValue();
9293
9294 SDValue ConstVec = N->getOperand(1);
9295 if (!isa<BuildVectorSDNode>(ConstVec))
9296 return SDValue();
9297
9298 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9299 int32_t IntBits = IntTy.getSizeInBits();
9300 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9301 return SDValue();
9302
9303 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9304 int32_t FloatBits = FloatTy.getSizeInBits();
9305 if (FloatBits != 32 && FloatBits != 64)
9306 return SDValue();
9307
9308 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9309 if (IntBits > FloatBits)
9310 return SDValue();
9311
9312 BitVector UndefElements;
9313 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9314 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9315 if (C == -1 || C == 0 || C > FloatBits)
9316 return SDValue();
9317
9318 MVT ResTy;
9319 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9320 switch (NumLanes) {
9321 default:
9322 return SDValue();
9323 case 2:
9324 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9325 break;
9326 case 4:
9327 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9328 break;
9329 }
9330
9331 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9332 return SDValue();
9333
9334 SDLoc DL(N);
9335 SDValue ConvInput = Op.getOperand(0);
9336 bool IsSigned = Opc == ISD::SINT_TO_FP;
9337 if (IntBits < FloatBits)
9338 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9339 ResTy, ConvInput);
9340
9341 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9342 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9343 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9344 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9345 DAG.getConstant(C, DL, MVT::i32));
9346}
9347
9348/// An EXTR instruction is made up of two shifts, ORed together. This helper
9349/// searches for and classifies those shifts.
9350static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9351 bool &FromHi) {
9352 if (N.getOpcode() == ISD::SHL)
9353 FromHi = false;
9354 else if (N.getOpcode() == ISD::SRL)
9355 FromHi = true;
9356 else
9357 return false;
9358
9359 if (!isa<ConstantSDNode>(N.getOperand(1)))
9360 return false;
9361
9362 ShiftAmount = N->getConstantOperandVal(1);
9363 Src = N->getOperand(0);
9364 return true;
9365}
9366
9367/// EXTR instruction extracts a contiguous chunk of bits from two existing
9368/// registers viewed as a high/low pair. This function looks for the pattern:
9369/// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9370/// with an EXTR. Can't quite be done in TableGen because the two immediates
9371/// aren't independent.
9372static SDValue tryCombineToEXTR(SDNode *N,
9373 TargetLowering::DAGCombinerInfo &DCI) {
9374 SelectionDAG &DAG = DCI.DAG;
9375 SDLoc DL(N);
9376 EVT VT = N->getValueType(0);
9377
9378 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9379
9380 if (VT != MVT::i32 && VT != MVT::i64)
9381 return SDValue();
9382
9383 SDValue LHS;
9384 uint32_t ShiftLHS = 0;
9385 bool LHSFromHi = false;
9386 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9387 return SDValue();
9388
9389 SDValue RHS;
9390 uint32_t ShiftRHS = 0;
9391 bool RHSFromHi = false;
9392 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9393 return SDValue();
9394
9395 // If they're both trying to come from the high part of the register, they're
9396 // not really an EXTR.
9397 if (LHSFromHi == RHSFromHi)
9398 return SDValue();
9399
9400 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9401 return SDValue();
9402
9403 if (LHSFromHi) {
9404 std::swap(LHS, RHS);
9405 std::swap(ShiftLHS, ShiftRHS);
9406 }
9407
9408 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9409 DAG.getConstant(ShiftRHS, DL, MVT::i64));
9410}
9411
9412static SDValue tryCombineToBSL(SDNode *N,
9413 TargetLowering::DAGCombinerInfo &DCI) {
9414 EVT VT = N->getValueType(0);
9415 SelectionDAG &DAG = DCI.DAG;
9416 SDLoc DL(N);
9417
9418 if (!VT.isVector())
9419 return SDValue();
9420
9421 SDValue N0 = N->getOperand(0);
9422 if (N0.getOpcode() != ISD::AND)
9423 return SDValue();
9424
9425 SDValue N1 = N->getOperand(1);
9426 if (N1.getOpcode() != ISD::AND)
9427 return SDValue();
9428
9429 // We only have to look for constant vectors here since the general, variable
9430 // case can be handled in TableGen.
9431 unsigned Bits = VT.getScalarSizeInBits();
9432 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9433 for (int i = 1; i >= 0; --i)
9434 for (int j = 1; j >= 0; --j) {
9435 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9436 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9437 if (!BVN0 || !BVN1)
9438 continue;
9439
9440 bool FoundMatch = true;
9441 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9442 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9443 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9444 if (!CN0 || !CN1 ||
9445 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9446 FoundMatch = false;
9447 break;
9448 }
9449 }
9450
9451 if (FoundMatch)
9452 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9453 N0->getOperand(1 - i), N1->getOperand(1 - j));
9454 }
9455
9456 return SDValue();
9457}
9458
9459static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9460 const AArch64Subtarget *Subtarget) {
9461 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9462 SelectionDAG &DAG = DCI.DAG;
9463 EVT VT = N->getValueType(0);
9464
9465 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9466 return SDValue();
9467
9468 if (SDValue Res = tryCombineToEXTR(N, DCI))
9469 return Res;
9470
9471 if (SDValue Res = tryCombineToBSL(N, DCI))
9472 return Res;
9473
9474 return SDValue();
9475}
9476
9477static SDValue performANDCombine(SDNode *N,
9478 TargetLowering::DAGCombinerInfo &DCI) {
9479 SelectionDAG &DAG = DCI.DAG;
9480 SDValue LHS = N->getOperand(0);
9481 EVT VT = N->getValueType(0);
9482 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9483 return SDValue();
9484
9485 BuildVectorSDNode *BVN =
9486 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9487 if (!BVN)
9488 return SDValue();
9489
9490 // AND does not accept an immediate, so check if we can use a BIC immediate
9491 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9492 // pattern in isel, because some immediates may be lowered to the preferred
9493 // (and x, (movi imm)) form, even though an mvni representation also exists.
9494 APInt DefBits(VT.getSizeInBits(), 0);
9495 APInt UndefBits(VT.getSizeInBits(), 0);
9496 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9497 SDValue NewOp;
9498
9499 DefBits = ~DefBits;
9500 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9501 DefBits, &LHS)) ||
9502 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9503 DefBits, &LHS)))
9504 return NewOp;
9505
9506 UndefBits = ~UndefBits;
9507 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9508 UndefBits, &LHS)) ||
9509 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9510 UndefBits, &LHS)))
9511 return NewOp;
9512 }
9513
9514 return SDValue();
9515}
9516
9517static SDValue performSRLCombine(SDNode *N,
9518 TargetLowering::DAGCombinerInfo &DCI) {
9519 SelectionDAG &DAG = DCI.DAG;
9520 EVT VT = N->getValueType(0);
9521 if (VT != MVT::i32 && VT != MVT::i64)
9522 return SDValue();
9523
9524 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9525 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9526 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9527 SDValue N0 = N->getOperand(0);
9528 if (N0.getOpcode() == ISD::BSWAP) {
9529 SDLoc DL(N);
9530 SDValue N1 = N->getOperand(1);
9531 SDValue N00 = N0.getOperand(0);
9532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9533 uint64_t ShiftAmt = C->getZExtValue();
9534 if (VT == MVT::i32 && ShiftAmt == 16 &&
9535 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9536 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9537 if (VT == MVT::i64 && ShiftAmt == 32 &&
9538 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9539 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9540 }
9541 }
9542 return SDValue();
9543}
9544
9545static SDValue performBitcastCombine(SDNode *N,
9546 TargetLowering::DAGCombinerInfo &DCI,
9547 SelectionDAG &DAG) {
9548 // Wait 'til after everything is legalized to try this. That way we have
9549 // legal vector types and such.
9550 if (DCI.isBeforeLegalizeOps())
9551 return SDValue();
9552
9553 // Remove extraneous bitcasts around an extract_subvector.
9554 // For example,
9555 // (v4i16 (bitconvert
9556 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9557 // becomes
9558 // (extract_subvector ((v8i16 ...), (i64 4)))
9559
9560 // Only interested in 64-bit vectors as the ultimate result.
9561 EVT VT = N->getValueType(0);
9562 if (!VT.isVector())
9563 return SDValue();
9564 if (VT.getSimpleVT().getSizeInBits() != 64)
9565 return SDValue();
9566 // Is the operand an extract_subvector starting at the beginning or halfway
9567 // point of the vector? A low half may also come through as an
9568 // EXTRACT_SUBREG, so look for that, too.
9569 SDValue Op0 = N->getOperand(0);
9570 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9571 !(Op0->isMachineOpcode() &&
9572 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9573 return SDValue();
9574 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9575 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9576 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9577 return SDValue();
9578 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9579 if (idx != AArch64::dsub)
9580 return SDValue();
9581 // The dsub reference is equivalent to a lane zero subvector reference.
9582 idx = 0;
9583 }
9584 // Look through the bitcast of the input to the extract.
9585 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9586 return SDValue();
9587 SDValue Source = Op0->getOperand(0)->getOperand(0);
9588 // If the source type has twice the number of elements as our destination
9589 // type, we know this is an extract of the high or low half of the vector.
9590 EVT SVT = Source->getValueType(0);
9591 if (!SVT.isVector() ||
9592 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9593 return SDValue();
9594
9595 LLVM_DEBUG(
9596 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9597
9598 // Create the simplified form to just extract the low or high half of the
9599 // vector directly rather than bothering with the bitcasts.
9600 SDLoc dl(N);
9601 unsigned NumElements = VT.getVectorNumElements();
9602 if (idx) {
9603 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9604 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9605 } else {
9606 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9607 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9608 Source, SubReg),
9609 0);
9610 }
9611}
9612
9613static SDValue performConcatVectorsCombine(SDNode *N,
9614 TargetLowering::DAGCombinerInfo &DCI,
9615 SelectionDAG &DAG) {
9616 SDLoc dl(N);
9617 EVT VT = N->getValueType(0);
9618 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9619
9620 // Optimize concat_vectors of truncated vectors, where the intermediate
9621 // type is illegal, to avoid said illegality, e.g.,
9622 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9623 // (v2i16 (truncate (v2i64)))))
9624 // ->
9625 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9626 // (v4i32 (bitcast (v2i64))),
9627 // <0, 2, 4, 6>)))
9628 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9629 // on both input and result type, so we might generate worse code.
9630 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9631 if (N->getNumOperands() == 2 &&
9632 N0->getOpcode() == ISD::TRUNCATE &&
9633 N1->getOpcode() == ISD::TRUNCATE) {
9634 SDValue N00 = N0->getOperand(0);
9635 SDValue N10 = N1->getOperand(0);
9636 EVT N00VT = N00.getValueType();
9637
9638 if (N00VT == N10.getValueType() &&
9639 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9640 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9641 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9642 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9643 for (size_t i = 0; i < Mask.size(); ++i)
9644 Mask[i] = i * 2;
9645 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9646 DAG.getVectorShuffle(
9647 MidVT, dl,
9648 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9649 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9650 }
9651 }
9652
9653 // Wait 'til after everything is legalized to try this. That way we have
9654 // legal vector types and such.
9655 if (DCI.isBeforeLegalizeOps())
9656 return SDValue();
9657
9658 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9659 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9660 // canonicalise to that.
9661 if (N0 == N1 && VT.getVectorNumElements() == 2) {
9662 assert(VT.getScalarSizeInBits() == 64);
9663 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9664 DAG.getConstant(0, dl, MVT::i64));
9665 }
9666
9667 // Canonicalise concat_vectors so that the right-hand vector has as few
9668 // bit-casts as possible before its real operation. The primary matching
9669 // destination for these operations will be the narrowing "2" instructions,
9670 // which depend on the operation being performed on this right-hand vector.
9671 // For example,
9672 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9673 // becomes
9674 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9675
9676 if (N1->getOpcode() != ISD::BITCAST)
9677 return SDValue();
9678 SDValue RHS = N1->getOperand(0);
9679 MVT RHSTy = RHS.getValueType().getSimpleVT();
9680 // If the RHS is not a vector, this is not the pattern we're looking for.
9681 if (!RHSTy.isVector())
9682 return SDValue();
9683
9684 LLVM_DEBUG(
9685 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9686
9687 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9688 RHSTy.getVectorNumElements() * 2);
9689 return DAG.getNode(ISD::BITCAST, dl, VT,
9690 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9691 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9692 RHS));
9693}
9694
9695static SDValue tryCombineFixedPointConvert(SDNode *N,
9696 TargetLowering::DAGCombinerInfo &DCI,
9697 SelectionDAG &DAG) {
9698 // Wait until after everything is legalized to try this. That way we have
9699 // legal vector types and such.
9700 if (DCI.isBeforeLegalizeOps())
9701 return SDValue();
9702 // Transform a scalar conversion of a value from a lane extract into a
9703 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9704 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9705 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9706 //
9707 // The second form interacts better with instruction selection and the
9708 // register allocator to avoid cross-class register copies that aren't
9709 // coalescable due to a lane reference.
9710
9711 // Check the operand and see if it originates from a lane extract.
9712 SDValue Op1 = N->getOperand(1);
9713 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9714 // Yep, no additional predication needed. Perform the transform.
9715 SDValue IID = N->getOperand(0);
9716 SDValue Shift = N->getOperand(2);
9717 SDValue Vec = Op1.getOperand(0);
9718 SDValue Lane = Op1.getOperand(1);
9719 EVT ResTy = N->getValueType(0);
9720 EVT VecResTy;
9721 SDLoc DL(N);
9722
9723 // The vector width should be 128 bits by the time we get here, even
9724 // if it started as 64 bits (the extract_vector handling will have
9725 // done so).
9726 assert(Vec.getValueSizeInBits() == 128 &&
9727 "unexpected vector size on extract_vector_elt!");
9728 if (Vec.getValueType() == MVT::v4i32)
9729 VecResTy = MVT::v4f32;
9730 else if (Vec.getValueType() == MVT::v2i64)
9731 VecResTy = MVT::v2f64;
9732 else
9733 llvm_unreachable("unexpected vector type!");
9734
9735 SDValue Convert =
9736 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9737 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9738 }
9739 return SDValue();
9740}
9741
9742// AArch64 high-vector "long" operations are formed by performing the non-high
9743// version on an extract_subvector of each operand which gets the high half:
9744//
9745// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9746//
9747// However, there are cases which don't have an extract_high explicitly, but
9748// have another operation that can be made compatible with one for free. For
9749// example:
9750//
9751// (dupv64 scalar) --> (extract_high (dup128 scalar))
9752//
9753// This routine does the actual conversion of such DUPs, once outer routines
9754// have determined that everything else is in order.
9755// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9756// similarly here.
9757static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
9758 switch (N.getOpcode()) {
9759 case AArch64ISD::DUP:
9760 case AArch64ISD::DUPLANE8:
9761 case AArch64ISD::DUPLANE16:
9762 case AArch64ISD::DUPLANE32:
9763 case AArch64ISD::DUPLANE64:
9764 case AArch64ISD::MOVI:
9765 case AArch64ISD::MOVIshift:
9766 case AArch64ISD::MOVIedit:
9767 case AArch64ISD::MOVImsl:
9768 case AArch64ISD::MVNIshift:
9769 case AArch64ISD::MVNImsl:
9770 break;
9771 default:
9772 // FMOV could be supported, but isn't very useful, as it would only occur
9773 // if you passed a bitcast' floating point immediate to an eligible long
9774 // integer op (addl, smull, ...).
9775 return SDValue();
9776 }
9777
9778 MVT NarrowTy = N.getSimpleValueType();
9779 if (!NarrowTy.is64BitVector())
9780 return SDValue();
9781
9782 MVT ElementTy = NarrowTy.getVectorElementType();
9783 unsigned NumElems = NarrowTy.getVectorNumElements();
9784 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
9785
9786 SDLoc dl(N);
9787 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9788 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
9789 DAG.getConstant(NumElems, dl, MVT::i64));
9790}
9791
9792static bool isEssentiallyExtractHighSubvector(SDValue N) {
9793 if (N.getOpcode() == ISD::BITCAST)
9794 N = N.getOperand(0);
9795 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9796 return false;
9797 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9798 N.getOperand(0).getValueType().getVectorNumElements() / 2;
9799}
9800
9801/// Helper structure to keep track of ISD::SET_CC operands.
9802struct GenericSetCCInfo {
9803 const SDValue *Opnd0;
9804 const SDValue *Opnd1;
9805 ISD::CondCode CC;
9806};
9807
9808/// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9809struct AArch64SetCCInfo {
9810 const SDValue *Cmp;
9811 AArch64CC::CondCode CC;
9812};
9813
9814/// Helper structure to keep track of SetCC information.
9815union SetCCInfo {
9816 GenericSetCCInfo Generic;
9817 AArch64SetCCInfo AArch64;
9818};
9819
9820/// Helper structure to be able to read SetCC information. If set to
9821/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9822/// GenericSetCCInfo.
9823struct SetCCInfoAndKind {
9824 SetCCInfo Info;
9825 bool IsAArch64;
9826};
9827
9828/// Check whether or not \p Op is a SET_CC operation, either a generic or
9829/// an
9830/// AArch64 lowered one.
9831/// \p SetCCInfo is filled accordingly.
9832/// \post SetCCInfo is meanginfull only when this function returns true.
9833/// \return True when Op is a kind of SET_CC operation.
9834static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9835 // If this is a setcc, this is straight forward.
9836 if (Op.getOpcode() == ISD::SETCC) {
9837 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9838 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9839 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9840 SetCCInfo.IsAArch64 = false;
9841 return true;
9842 }
9843 // Otherwise, check if this is a matching csel instruction.
9844 // In other words:
9845 // - csel 1, 0, cc
9846 // - csel 0, 1, !cc
9847 if (Op.getOpcode() != AArch64ISD::CSEL)
9848 return false;
9849 // Set the information about the operands.
9850 // TODO: we want the operands of the Cmp not the csel
9851 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9852 SetCCInfo.IsAArch64 = true;
9853 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9854 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9855
9856 // Check that the operands matches the constraints:
9857 // (1) Both operands must be constants.
9858 // (2) One must be 1 and the other must be 0.
9859 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9860 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9861
9862 // Check (1).
9863 if (!TValue || !FValue)
9864 return false;
9865
9866 // Check (2).
9867 if (!TValue->isOne()) {
9868 // Update the comparison when we are interested in !cc.
9869 std::swap(TValue, FValue);
9870 SetCCInfo.Info.AArch64.CC =
9871 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9872 }
9873 return TValue->isOne() && FValue->isNullValue();
9874}
9875
9876// Returns true if Op is setcc or zext of setcc.
9877static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9878 if (isSetCC(Op, Info))
9879 return true;
9880 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9881 isSetCC(Op->getOperand(0), Info));
9882}
9883
9884// The folding we want to perform is:
9885// (add x, [zext] (setcc cc ...) )
9886// -->
9887// (csel x, (add x, 1), !cc ...)
9888//
9889// The latter will get matched to a CSINC instruction.
9890static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9891 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9892 SDValue LHS = Op->getOperand(0);
9893 SDValue RHS = Op->getOperand(1);
9894 SetCCInfoAndKind InfoAndKind;
9895
9896 // If neither operand is a SET_CC, give up.
9897 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9898 std::swap(LHS, RHS);
9899 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9900 return SDValue();
9901 }
9902
9903 // FIXME: This could be generatized to work for FP comparisons.
9904 EVT CmpVT = InfoAndKind.IsAArch64
9905 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9906 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9907 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9908 return SDValue();
9909
9910 SDValue CCVal;
9911 SDValue Cmp;
9912 SDLoc dl(Op);
9913 if (InfoAndKind.IsAArch64) {
9914 CCVal = DAG.getConstant(
9915 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9916 MVT::i32);
9917 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9918 } else
9919 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9920 *InfoAndKind.Info.Generic.Opnd1,
9921 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT),
9922 CCVal, DAG, dl);
9923
9924 EVT VT = Op->getValueType(0);
9925 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
9926 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9927}
9928
9929// The basic add/sub long vector instructions have variants with "2" on the end
9930// which act on the high-half of their inputs. They are normally matched by
9931// patterns like:
9932//
9933// (add (zeroext (extract_high LHS)),
9934// (zeroext (extract_high RHS)))
9935// -> uaddl2 vD, vN, vM
9936//
9937// However, if one of the extracts is something like a duplicate, this
9938// instruction can still be used profitably. This function puts the DAG into a
9939// more appropriate form for those patterns to trigger.
9940static SDValue performAddSubLongCombine(SDNode *N,
9941 TargetLowering::DAGCombinerInfo &DCI,
9942 SelectionDAG &DAG) {
9943 if (DCI.isBeforeLegalizeOps())
9944 return SDValue();
9945
9946 MVT VT = N->getSimpleValueType(0);
9947 if (!VT.is128BitVector()) {
9948 if (N->getOpcode() == ISD::ADD)
9949 return performSetccAddFolding(N, DAG);
9950 return SDValue();
9951 }
9952
9953 // Make sure both branches are extended in the same way.
9954 SDValue LHS = N->getOperand(0);
9955 SDValue RHS = N->getOperand(1);
9956 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9957 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9958 LHS.getOpcode() != RHS.getOpcode())
9959 return SDValue();
9960
9961 unsigned ExtType = LHS.getOpcode();
9962
9963 // It's not worth doing if at least one of the inputs isn't already an
9964 // extract, but we don't know which it'll be so we have to try both.
9965 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
9966 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9967 if (!RHS.getNode())
9968 return SDValue();
9969
9970 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9971 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
9972 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9973 if (!LHS.getNode())
9974 return SDValue();
9975
9976 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9977 }
9978
9979 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9980}
9981
9982// Massage DAGs which we can use the high-half "long" operations on into
9983// something isel will recognize better. E.g.
9984//
9985// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9986// (aarch64_neon_umull (extract_high (v2i64 vec)))
9987// (extract_high (v2i64 (dup128 scalar)))))
9988//
9989static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
9990 TargetLowering::DAGCombinerInfo &DCI,
9991 SelectionDAG &DAG) {
9992 if (DCI.isBeforeLegalizeOps())
9993 return SDValue();
9994
9995 SDValue LHS = N->getOperand(1);
9996 SDValue RHS = N->getOperand(2);
9997 assert(LHS.getValueType().is64BitVector() &&
9998 RHS.getValueType().is64BitVector() &&
9999 "unexpected shape for long operation");
10000
10001 // Either node could be a DUP, but it's not worth doing both of them (you'd
10002 // just as well use the non-high version) so look for a corresponding extract
10003 // operation on the other "wing".
10004 if (isEssentiallyExtractHighSubvector(LHS)) {
10005 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10006 if (!RHS.getNode())
10007 return SDValue();
10008 } else if (isEssentiallyExtractHighSubvector(RHS)) {
10009 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10010 if (!LHS.getNode())
10011 return SDValue();
10012 }
10013
10014 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10015 N->getOperand(0), LHS, RHS);
10016}
10017
10018static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10019 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10020 unsigned ElemBits = ElemTy.getSizeInBits();
10021
10022 int64_t ShiftAmount;
10023 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10024 APInt SplatValue, SplatUndef;
10025 unsigned SplatBitSize;
10026 bool HasAnyUndefs;
10027 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10028 HasAnyUndefs, ElemBits) ||
10029 SplatBitSize != ElemBits)
10030 return SDValue();
10031
10032 ShiftAmount = SplatValue.getSExtValue();
10033 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10034 ShiftAmount = CVN->getSExtValue();
10035 } else
10036 return SDValue();
10037
10038 unsigned Opcode;
10039 bool IsRightShift;
10040 switch (IID) {
10041 default:
10042 llvm_unreachable("Unknown shift intrinsic");
10043 case Intrinsic::aarch64_neon_sqshl:
10044 Opcode = AArch64ISD::SQSHL_I;
10045 IsRightShift = false;
10046 break;
10047 case Intrinsic::aarch64_neon_uqshl:
10048 Opcode = AArch64ISD::UQSHL_I;
10049 IsRightShift = false;
10050 break;
10051 case Intrinsic::aarch64_neon_srshl:
10052 Opcode = AArch64ISD::SRSHR_I;
10053 IsRightShift = true;
10054 break;
10055 case Intrinsic::aarch64_neon_urshl:
10056 Opcode = AArch64ISD::URSHR_I;
10057 IsRightShift = true;
10058 break;
10059 case Intrinsic::aarch64_neon_sqshlu:
10060 Opcode = AArch64ISD::SQSHLU_I;
10061 IsRightShift = false;
10062 break;
10063 }
10064
10065 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10066 SDLoc dl(N);
10067 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10068 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10069 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10070 SDLoc dl(N);
10071 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10072 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10073 }
10074
10075 return SDValue();
10076}
10077
10078// The CRC32[BH] instructions ignore the high bits of their data operand. Since
10079// the intrinsics must be legal and take an i32, this means there's almost
10080// certainly going to be a zext in the DAG which we can eliminate.
10081static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10082 SDValue AndN = N->getOperand(2);
10083 if (AndN.getOpcode() != ISD::AND)
10084 return SDValue();
10085
10086 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10087 if (!CMask || CMask->getZExtValue() != Mask)
10088 return SDValue();
10089
10090 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10091 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10092}
10093
10094static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10095 SelectionDAG &DAG) {
10096 SDLoc dl(N);
10097 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10098 DAG.getNode(Opc, dl,
10099 N->getOperand(1).getSimpleValueType(),
10100 N->getOperand(1)),
10101 DAG.getConstant(0, dl, MVT::i64));
10102}
10103
10104static SDValue performIntrinsicCombine(SDNode *N,
10105 TargetLowering::DAGCombinerInfo &DCI,
10106 const AArch64Subtarget *Subtarget) {
10107 SelectionDAG &DAG = DCI.DAG;
10108 unsigned IID = getIntrinsicID(N);
10109 switch (IID) {
10110 default:
10111 break;
10112 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10113 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10114 return tryCombineFixedPointConvert(N, DCI, DAG);
10115 case Intrinsic::aarch64_neon_saddv:
10116 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10117 case Intrinsic::aarch64_neon_uaddv:
10118 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10119 case Intrinsic::aarch64_neon_sminv:
10120 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10121 case Intrinsic::aarch64_neon_uminv:
10122 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10123 case Intrinsic::aarch64_neon_smaxv:
10124 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10125 case Intrinsic::aarch64_neon_umaxv:
10126 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10127 case Intrinsic::aarch64_neon_fmax:
10128 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10129 N->getOperand(1), N->getOperand(2));
10130 case Intrinsic::aarch64_neon_fmin:
10131 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10132 N->getOperand(1), N->getOperand(2));
10133 case Intrinsic::aarch64_neon_fmaxnm:
10134 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10135 N->getOperand(1), N->getOperand(2));
10136 case Intrinsic::aarch64_neon_fminnm:
10137 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10138 N->getOperand(1), N->getOperand(2));
10139 case Intrinsic::aarch64_neon_smull:
10140 case Intrinsic::aarch64_neon_umull:
10141 case Intrinsic::aarch64_neon_pmull:
10142 case Intrinsic::aarch64_neon_sqdmull:
10143 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10144 case Intrinsic::aarch64_neon_sqshl:
10145 case Intrinsic::aarch64_neon_uqshl:
10146 case Intrinsic::aarch64_neon_sqshlu:
10147 case Intrinsic::aarch64_neon_srshl:
10148 case Intrinsic::aarch64_neon_urshl:
10149 return tryCombineShiftImm(IID, N, DAG);
10150 case Intrinsic::aarch64_crc32b:
10151 case Intrinsic::aarch64_crc32cb:
10152 return tryCombineCRC32(0xff, N, DAG);
10153 case Intrinsic::aarch64_crc32h:
10154 case Intrinsic::aarch64_crc32ch:
10155 return tryCombineCRC32(0xffff, N, DAG);
10156 }
10157 return SDValue();
10158}
10159
10160static SDValue performExtendCombine(SDNode *N,
10161 TargetLowering::DAGCombinerInfo &DCI,
10162 SelectionDAG &DAG) {
10163 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10164 // we can convert that DUP into another extract_high (of a bigger DUP), which
10165 // helps the backend to decide that an sabdl2 would be useful, saving a real
10166 // extract_high operation.
10167 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
10168 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
10169 SDNode *ABDNode = N->getOperand(0).getNode();
10170 unsigned IID = getIntrinsicID(ABDNode);
10171 if (IID == Intrinsic::aarch64_neon_sabd ||
10172 IID == Intrinsic::aarch64_neon_uabd) {
10173 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10174 if (!NewABD.getNode())
10175 return SDValue();
10176
10177 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10178 NewABD);
10179 }
10180 }
10181
10182 // This is effectively a custom type legalization for AArch64.
10183 //
10184 // Type legalization will split an extend of a small, legal, type to a larger
10185 // illegal type by first splitting the destination type, often creating
10186 // illegal source types, which then get legalized in isel-confusing ways,
10187 // leading to really terrible codegen. E.g.,
10188 // %result = v8i32 sext v8i8 %value
10189 // becomes
10190 // %losrc = extract_subreg %value, ...
10191 // %hisrc = extract_subreg %value, ...
10192 // %lo = v4i32 sext v4i8 %losrc
10193 // %hi = v4i32 sext v4i8 %hisrc
10194 // Things go rapidly downhill from there.
10195 //
10196 // For AArch64, the [sz]ext vector instructions can only go up one element
10197 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10198 // take two instructions.
10199 //
10200 // This implies that the most efficient way to do the extend from v8i8
10201 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10202 // the normal splitting to happen for the v8i16->v8i32.
10203
10204 // This is pre-legalization to catch some cases where the default
10205 // type legalization will create ill-tempered code.
10206 if (!DCI.isBeforeLegalizeOps())
10207 return SDValue();
10208
10209 // We're only interested in cleaning things up for non-legal vector types
10210 // here. If both the source and destination are legal, things will just
10211 // work naturally without any fiddling.
10212 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10213 EVT ResVT = N->getValueType(0);
10214 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10215 return SDValue();
10216 // If the vector type isn't a simple VT, it's beyond the scope of what
10217 // we're worried about here. Let legalization do its thing and hope for
10218 // the best.
10219 SDValue Src = N->getOperand(0);
10220 EVT SrcVT = Src->getValueType(0);
10221 if (!ResVT.isSimple() || !SrcVT.isSimple())
10222 return SDValue();
10223
10224 // If the source VT is a 64-bit vector, we can play games and get the
10225 // better results we want.
10226 if (SrcVT.getSizeInBits() != 64)
10227 return SDValue();
10228
10229 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
10230 unsigned ElementCount = SrcVT.getVectorNumElements();
10231 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10232 SDLoc DL(N);
10233 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10234
10235 // Now split the rest of the operation into two halves, each with a 64
10236 // bit source.
10237 EVT LoVT, HiVT;
10238 SDValue Lo, Hi;
10239 unsigned NumElements = ResVT.getVectorNumElements();
10240 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10241 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10242 ResVT.getVectorElementType(), NumElements / 2);
10243
10244 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10245 LoVT.getVectorNumElements());
10246 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10247 DAG.getConstant(0, DL, MVT::i64));
10248 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10249 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10250 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10251 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10252
10253 // Now combine the parts back together so we still have a single result
10254 // like the combiner expects.
10255 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10256}
10257
10258static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10259 SDValue SplatVal, unsigned NumVecElts) {
10260 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
10261 unsigned OrigAlignment = St.getAlignment();
10262 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10263
10264 // Create scalar stores. This is at least as good as the code sequence for a
10265 // split unaligned store which is a dup.s, ext.b, and two stores.
10266 // Most of the time the three stores should be replaced by store pair
10267 // instructions (stp).
10268 SDLoc DL(&St);
10269 SDValue BasePtr = St.getBasePtr();
10270 uint64_t BaseOffset = 0;
10271
10272 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10273 SDValue NewST1 =
10274 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10275 OrigAlignment, St.getMemOperand()->getFlags());
10276
10277 // As this in ISel, we will not merge this add which may degrade results.
10278 if (BasePtr->getOpcode() == ISD::ADD &&
10279 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10280 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10281 BasePtr = BasePtr->getOperand(0);
10282 }
10283
10284 unsigned Offset = EltOffset;
10285 while (--NumVecElts) {
10286 unsigned Alignment = MinAlign(OrigAlignment, Offset);
10287 SDValue OffsetPtr =
10288 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10289 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10290 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10291 PtrInfo.getWithOffset(Offset), Alignment,
10292 St.getMemOperand()->getFlags());
10293 Offset += EltOffset;
10294 }
10295 return NewST1;
10296}
10297
10298/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10299/// load store optimizer pass will merge them to store pair stores. This should
10300/// be better than a movi to create the vector zero followed by a vector store
10301/// if the zero constant is not re-used, since one instructions and one register
10302/// live range will be removed.
10303///
10304/// For example, the final generated code should be:
10305///
10306/// stp xzr, xzr, [x0]
10307///
10308/// instead of:
10309///
10310/// movi v0.2d, #0
10311/// str q0, [x0]
10312///
10313static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10314 SDValue StVal = St.getValue();
10315 EVT VT = StVal.getValueType();
10316
10317 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10318 // 2, 3 or 4 i32 elements.
10319 int NumVecElts = VT.getVectorNumElements();
10320 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10321 VT.getVectorElementType().getSizeInBits() == 64) ||
10322 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10323 VT.getVectorElementType().getSizeInBits() == 32)))
10324 return SDValue();
10325
10326 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10327 return SDValue();
10328
10329 // If the zero constant has more than one use then the vector store could be
10330 // better since the constant mov will be amortized and stp q instructions
10331 // should be able to be formed.
10332 if (!StVal.hasOneUse())
10333 return SDValue();
10334
10335 // If the store is truncating then it's going down to i16 or smaller, which
10336 // means it can be implemented in a single store anyway.
10337 if (St.isTruncatingStore())
10338 return SDValue();
10339
10340 // If the immediate offset of the address operand is too large for the stp
10341 // instruction, then bail out.
10342 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10343 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10344 if (Offset < -512 || Offset > 504)
10345 return SDValue();
10346 }
10347
10348 for (int I = 0; I < NumVecElts; ++I) {
10349 SDValue EltVal = StVal.getOperand(I);
10350 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10351 return SDValue();
10352 }
10353
10354 // Use a CopyFromReg WZR/XZR here to prevent
10355 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10356 SDLoc DL(&St);
10357 unsigned ZeroReg;
10358 EVT ZeroVT;
10359 if (VT.getVectorElementType().getSizeInBits() == 32) {
10360 ZeroReg = AArch64::WZR;
10361 ZeroVT = MVT::i32;
10362 } else {
10363 ZeroReg = AArch64::XZR;
10364 ZeroVT = MVT::i64;
10365 }
10366 SDValue SplatVal =
10367 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10368 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10369}
10370
10371/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10372/// value. The load store optimizer pass will merge them to store pair stores.
10373/// This has better performance than a splat of the scalar followed by a split
10374/// vector store. Even if the stores are not merged it is four stores vs a dup,
10375/// followed by an ext.b and two stores.
10376static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10377 SDValue StVal = St.getValue();
10378 EVT VT = StVal.getValueType();
10379
10380 // Don't replace floating point stores, they possibly won't be transformed to
10381 // stp because of the store pair suppress pass.
10382 if (VT.isFloatingPoint())
10383 return SDValue();
10384
10385 // We can express a splat as store pair(s) for 2 or 4 elements.
10386 unsigned NumVecElts = VT.getVectorNumElements();
10387 if (NumVecElts != 4 && NumVecElts != 2)
10388 return SDValue();
10389
10390 // If the store is truncating then it's going down to i16 or smaller, which
10391 // means it can be implemented in a single store anyway.
10392 if (St.isTruncatingStore())
10393 return SDValue();
10394
10395 // Check that this is a splat.
10396 // Make sure that each of the relevant vector element locations are inserted
10397 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10398 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10399 SDValue SplatVal;
10400 for (unsigned I = 0; I < NumVecElts; ++I) {
10401 // Check for insert vector elements.
10402 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10403 return SDValue();
10404
10405 // Check that same value is inserted at each vector element.
10406 if (I == 0)
10407 SplatVal = StVal.getOperand(1);
10408 else if (StVal.getOperand(1) != SplatVal)
10409 return SDValue();
10410
10411 // Check insert element index.
10412 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10413 if (!CIndex)
10414 return SDValue();
10415 uint64_t IndexVal = CIndex->getZExtValue();
10416 if (IndexVal >= NumVecElts)
10417 return SDValue();
10418 IndexNotInserted.reset(IndexVal);
10419
10420 StVal = StVal.getOperand(0);
10421 }
10422 // Check that all vector element locations were inserted to.
10423 if (IndexNotInserted.any())
10424 return SDValue();
10425
10426 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10427}
10428
10429static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10430 SelectionDAG &DAG,
10431 const AArch64Subtarget *Subtarget) {
10432
10433 StoreSDNode *S = cast<StoreSDNode>(N);
10434 if (S->isVolatile() || S->isIndexed())
10435 return SDValue();
10436
10437 SDValue StVal = S->getValue();
10438 EVT VT = StVal.getValueType();
10439 if (!VT.isVector())
10440 return SDValue();
10441
10442 // If we get a splat of zeros, convert this vector store to a store of
10443 // scalars. They will be merged into store pairs of xzr thereby removing one
10444 // instruction and one register.
10445 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10446 return ReplacedZeroSplat;
10447
10448 // FIXME: The logic for deciding if an unaligned store should be split should
10449 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10450 // a call to that function here.
10451
10452 if (!Subtarget->isMisaligned128StoreSlow())
10453 return SDValue();
10454
10455 // Don't split at -Oz.
10456 if (DAG.getMachineFunction().getFunction().hasMinSize())
10457 return SDValue();
10458
10459 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10460 // those up regresses performance on micro-benchmarks and olden/bh.
10461 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10462 return SDValue();
10463
10464 // Split unaligned 16B stores. They are terrible for performance.
10465 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10466 // extensions can use this to mark that it does not want splitting to happen
10467 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10468 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10469 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10470 S->getAlignment() <= 2)
10471 return SDValue();
10472
10473 // If we get a splat of a scalar convert this vector store to a store of
10474 // scalars. They will be merged into store pairs thereby removing two
10475 // instructions.
10476 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10477 return ReplacedSplat;
10478
10479 SDLoc DL(S);
10480 unsigned NumElts = VT.getVectorNumElements() / 2;
10481 // Split VT into two.
10482 EVT HalfVT =
10483 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10484 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10485 DAG.getConstant(0, DL, MVT::i64));
10486 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10487 DAG.getConstant(NumElts, DL, MVT::i64));
10488 SDValue BasePtr = S->getBasePtr();
10489 SDValue NewST1 =
10490 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10491 S->getAlignment(), S->getMemOperand()->getFlags());
10492 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10493 DAG.getConstant(8, DL, MVT::i64));
10494 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10495 S->getPointerInfo(), S->getAlignment(),
10496 S->getMemOperand()->getFlags());
10497}
10498
10499/// Target-specific DAG combine function for post-increment LD1 (lane) and
10500/// post-increment LD1R.
10501static SDValue performPostLD1Combine(SDNode *N,
10502 TargetLowering::DAGCombinerInfo &DCI,
10503 bool IsLaneOp) {
10504 if (DCI.isBeforeLegalizeOps())
10505 return SDValue();
10506
10507 SelectionDAG &DAG = DCI.DAG;
10508 EVT VT = N->getValueType(0);
10509
10510 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10511 SDNode *LD = N->getOperand(LoadIdx).getNode();
10512 // If it is not LOAD, can not do such combine.
10513 if (LD->getOpcode() != ISD::LOAD)
10514 return SDValue();
10515
10516 // The vector lane must be a constant in the LD1LANE opcode.
10517 SDValue Lane;
10518 if (IsLaneOp) {
10519 Lane = N->getOperand(2);
10520 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10521 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10522 return SDValue();
10523 }
10524
10525 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10526 EVT MemVT = LoadSDN->getMemoryVT();
10527 // Check if memory operand is the same type as the vector element.
10528 if (MemVT != VT.getVectorElementType())
10529 return SDValue();
10530
10531 // Check if there are other uses. If so, do not combine as it will introduce
10532 // an extra load.
10533 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10534 ++UI) {
10535 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10536 continue;
10537 if (*UI != N)
10538 return SDValue();
10539 }
10540
10541 SDValue Addr = LD->getOperand(1);
10542 SDValue Vector = N->getOperand(0);
10543 // Search for a use of the address operand that is an increment.
10544 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10545 Addr.getNode()->use_end(); UI != UE; ++UI) {
10546 SDNode *User = *UI;
10547 if (User->getOpcode() != ISD::ADD
10548 || UI.getUse().getResNo() != Addr.getResNo())
10549 continue;
10550
10551 // If the increment is a constant, it must match the memory ref size.
10552 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10553 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10554 uint32_t IncVal = CInc->getZExtValue();
10555 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10556 if (IncVal != NumBytes)
10557 continue;
10558 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10559 }
10560
10561 // To avoid cycle construction make sure that neither the load nor the add
10562 // are predecessors to each other or the Vector.
10563 SmallPtrSet<const SDNode *, 32> Visited;
10564 SmallVector<const SDNode *, 16> Worklist;
10565 Visited.insert(N);
10566 Worklist.push_back(User);
10567 Worklist.push_back(LD);
10568 Worklist.push_back(Vector.getNode());
10569 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10570 SDNode::hasPredecessorHelper(User, Visited, Worklist))
10571 continue;
10572
10573 SmallVector<SDValue, 8> Ops;
10574 Ops.push_back(LD->getOperand(0)); // Chain
10575 if (IsLaneOp) {
10576 Ops.push_back(Vector); // The vector to be inserted
10577 Ops.push_back(Lane); // The lane to be inserted in the vector
10578 }
10579 Ops.push_back(Addr);
10580 Ops.push_back(Inc);
10581
10582 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10583 SDVTList SDTys = DAG.getVTList(Tys);
10584 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10585 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10586 MemVT,
10587 LoadSDN->getMemOperand());
10588
10589 // Update the uses.
10590 SDValue NewResults[] = {
10591 SDValue(LD, 0), // The result of load
10592 SDValue(UpdN.getNode(), 2) // Chain
10593 };
10594 DCI.CombineTo(LD, NewResults);
10595 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10596 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10597
10598 break;
10599 }
10600 return SDValue();
10601}
10602
10603/// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10604/// address translation.
10605static bool performTBISimplification(SDValue Addr,
10606 TargetLowering::DAGCombinerInfo &DCI,
10607 SelectionDAG &DAG) {
10608 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10609 KnownBits Known;
10610 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10611 !DCI.isBeforeLegalizeOps());
10612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10613 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10614 DCI.CommitTargetLoweringOpt(TLO);
10615 return true;
10616 }
10617 return false;
10618}
10619
10620static SDValue performSTORECombine(SDNode *N,
10621 TargetLowering::DAGCombinerInfo &DCI,
10622 SelectionDAG &DAG,
10623 const AArch64Subtarget *Subtarget) {
10624 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10625 return Split;
10626
10627 if (Subtarget->supportsAddressTopByteIgnored() &&
10628 performTBISimplification(N->getOperand(2), DCI, DAG))
10629 return SDValue(N, 0);
10630
10631 return SDValue();
10632}
10633
10634
10635/// Target-specific DAG combine function for NEON load/store intrinsics
10636/// to merge base address updates.
10637static SDValue performNEONPostLDSTCombine(SDNode *N,
10638 TargetLowering::DAGCombinerInfo &DCI,
10639 SelectionDAG &DAG) {
10640 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10641 return SDValue();
10642
10643 unsigned AddrOpIdx = N->getNumOperands() - 1;
10644 SDValue Addr = N->getOperand(AddrOpIdx);
10645
10646 // Search for a use of the address operand that is an increment.
10647 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10648 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10649 SDNode *User = *UI;
10650 if (User->getOpcode() != ISD::ADD ||
10651 UI.getUse().getResNo() != Addr.getResNo())
10652 continue;
10653
10654 // Check that the add is independent of the load/store. Otherwise, folding
10655 // it would create a cycle.
10656 SmallPtrSet<const SDNode *, 32> Visited;
10657 SmallVector<const SDNode *, 16> Worklist;
10658 Visited.insert(Addr.getNode());
10659 Worklist.push_back(N);
10660 Worklist.push_back(User);
10661 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10662 SDNode::hasPredecessorHelper(User, Visited, Worklist))
10663 continue;
10664
10665 // Find the new opcode for the updating load/store.
10666 bool IsStore = false;
10667 bool IsLaneOp = false;
10668 bool IsDupOp = false;
10669 unsigned NewOpc = 0;
10670 unsigned NumVecs = 0;
10671 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10672 switch (IntNo) {
10673 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10674 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10675 NumVecs = 2; break;
10676 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10677 NumVecs = 3; break;
10678 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10679 NumVecs = 4; break;
10680 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10681 NumVecs = 2; IsStore = true; break;
10682 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10683 NumVecs = 3; IsStore = true; break;
10684 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10685 NumVecs = 4; IsStore = true; break;
10686 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10687 NumVecs = 2; break;
10688 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10689 NumVecs = 3; break;
10690 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10691 NumVecs = 4; break;
10692 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10693 NumVecs = 2; IsStore = true; break;
10694 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10695 NumVecs = 3; IsStore = true; break;
10696 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10697 NumVecs = 4; IsStore = true; break;
10698 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10699 NumVecs = 2; IsDupOp = true; break;
10700 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10701 NumVecs = 3; IsDupOp = true; break;
10702 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10703 NumVecs = 4; IsDupOp = true; break;
10704 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10705 NumVecs = 2; IsLaneOp = true; break;
10706 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10707 NumVecs = 3; IsLaneOp = true; break;
10708 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10709 NumVecs = 4; IsLaneOp = true; break;
10710 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10711 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10712 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10713 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10714 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10715 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10716 }
10717
10718 EVT VecTy;
10719 if (IsStore)
10720 VecTy = N->getOperand(2).getValueType();
10721 else
10722 VecTy = N->getValueType(0);
10723
10724 // If the increment is a constant, it must match the memory ref size.
10725 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10726 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10727 uint32_t IncVal = CInc->getZExtValue();
10728 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10729 if (IsLaneOp || IsDupOp)
10730 NumBytes /= VecTy.getVectorNumElements();
10731 if (IncVal != NumBytes)
10732 continue;
10733 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10734 }
10735 SmallVector<SDValue, 8> Ops;
10736 Ops.push_back(N->getOperand(0)); // Incoming chain
10737 // Load lane and store have vector list as input.
10738 if (IsLaneOp || IsStore)
10739 for (unsigned i = 2; i < AddrOpIdx; ++i)
10740 Ops.push_back(N->getOperand(i));
10741 Ops.push_back(Addr); // Base register
10742 Ops.push_back(Inc);
10743
10744 // Return Types.
10745 EVT Tys[6];
10746 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10747 unsigned n;
10748 for (n = 0; n < NumResultVecs; ++n)
10749 Tys[n] = VecTy;
10750 Tys[n++] = MVT::i64; // Type of write back register
10751 Tys[n] = MVT::Other; // Type of the chain
10752 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
10753
10754 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10755 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10756 MemInt->getMemoryVT(),
10757 MemInt->getMemOperand());
10758
10759 // Update the uses.
10760 std::vector<SDValue> NewResults;
10761 for (unsigned i = 0; i < NumResultVecs; ++i) {
10762 NewResults.push_back(SDValue(UpdN.getNode(), i));
10763 }
10764 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10765 DCI.CombineTo(N, NewResults);
10766 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10767
10768 break;
10769 }
10770 return SDValue();
10771}
10772
10773// Checks to see if the value is the prescribed width and returns information
10774// about its extension mode.
10775static
10776bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10777 ExtType = ISD::NON_EXTLOAD;
10778 switch(V.getNode()->getOpcode()) {
10779 default:
10780 return false;
10781 case ISD::LOAD: {
10782 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10783 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10784 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10785 ExtType = LoadNode->getExtensionType();
10786 return true;
10787 }
10788 return false;
10789 }
10790 case ISD::AssertSext: {
10791 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10792 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10793 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10794 ExtType = ISD::SEXTLOAD;
10795 return true;
10796 }
10797 return false;
10798 }
10799 case ISD::AssertZext: {
10800 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10801 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10802 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10803 ExtType = ISD::ZEXTLOAD;
10804 return true;
10805 }
10806 return false;
10807 }
10808 case ISD::Constant:
10809 case ISD::TargetConstant: {
10810 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10811 1LL << (width - 1);
10812 }
10813 }
10814
10815 return true;
10816}
10817
10818// This function does a whole lot of voodoo to determine if the tests are
10819// equivalent without and with a mask. Essentially what happens is that given a
10820// DAG resembling:
10821//
10822// +-------------+ +-------------+ +-------------+ +-------------+
10823// | Input | | AddConstant | | CompConstant| | CC |
10824// +-------------+ +-------------+ +-------------+ +-------------+
10825// | | | |
10826// V V | +----------+
10827// +-------------+ +----+ | |
10828// | ADD | |0xff| | |
10829// +-------------+ +----+ | |
10830// | | | |
10831// V V | |
10832// +-------------+ | |
10833// | AND | | |
10834// +-------------+ | |
10835// | | |
10836// +-----+ | |
10837// | | |
10838// V V V
10839// +-------------+
10840// | CMP |
10841// +-------------+
10842//
10843// The AND node may be safely removed for some combinations of inputs. In
10844// particular we need to take into account the extension type of the Input,
10845// the exact values of AddConstant, CompConstant, and CC, along with the nominal
10846// width of the input (this can work for any width inputs, the above graph is
10847// specific to 8 bits.
10848//
10849// The specific equations were worked out by generating output tables for each
10850// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10851// problem was simplified by working with 4 bit inputs, which means we only
10852// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10853// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10854// patterns present in both extensions (0,7). For every distinct set of
10855// AddConstant and CompConstants bit patterns we can consider the masked and
10856// unmasked versions to be equivalent if the result of this function is true for
10857// all 16 distinct bit patterns of for the current extension type of Input (w0).
10858//
10859// sub w8, w0, w1
10860// and w10, w8, #0x0f
10861// cmp w8, w2
10862// cset w9, AArch64CC
10863// cmp w10, w2
10864// cset w11, AArch64CC
10865// cmp w9, w11
10866// cset w0, eq
10867// ret
10868//
10869// Since the above function shows when the outputs are equivalent it defines
10870// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10871// would be expensive to run during compiles. The equations below were written
10872// in a test harness that confirmed they gave equivalent outputs to the above
10873// for all inputs function, so they can be used determine if the removal is
10874// legal instead.
10875//
10876// isEquivalentMaskless() is the code for testing if the AND can be removed
10877// factored out of the DAG recognition as the DAG can take several forms.
10878
10879static bool isEquivalentMaskless(unsigned CC, unsigned width,
10880 ISD::LoadExtType ExtType, int AddConstant,
10881 int CompConstant) {
10882 // By being careful about our equations and only writing the in term
10883 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10884 // make them generally applicable to all bit widths.
10885 int MaxUInt = (1 << width);
10886
10887 // For the purposes of these comparisons sign extending the type is
10888 // equivalent to zero extending the add and displacing it by half the integer
10889 // width. Provided we are careful and make sure our equations are valid over
10890 // the whole range we can just adjust the input and avoid writing equations
10891 // for sign extended inputs.
10892 if (ExtType == ISD::SEXTLOAD)
10893 AddConstant -= (1 << (width-1));
10894
10895 switch(CC) {
10896 case AArch64CC::LE:
10897 case AArch64CC::GT:
10898 if ((AddConstant == 0) ||
10899 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10900 (AddConstant >= 0 && CompConstant < 0) ||
10901 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10902 return true;
10903 break;
10904 case AArch64CC::LT:
10905 case AArch64CC::GE:
10906 if ((AddConstant == 0) ||
10907 (AddConstant >= 0 && CompConstant <= 0) ||
10908 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10909 return true;
10910 break;
10911 case AArch64CC::HI:
10912 case AArch64CC::LS:
10913 if ((AddConstant >= 0 && CompConstant < 0) ||
10914 (AddConstant <= 0 && CompConstant >= -1 &&
10915 CompConstant < AddConstant + MaxUInt))
10916 return true;
10917 break;
10918 case AArch64CC::PL:
10919 case AArch64CC::MI:
10920 if ((AddConstant == 0) ||
10921 (AddConstant > 0 && CompConstant <= 0) ||
10922 (AddConstant < 0 && CompConstant <= AddConstant))
10923 return true;
10924 break;
10925 case AArch64CC::LO:
10926 case AArch64CC::HS:
10927 if ((AddConstant >= 0 && CompConstant <= 0) ||
10928 (AddConstant <= 0 && CompConstant >= 0 &&
10929 CompConstant <= AddConstant + MaxUInt))
10930 return true;
10931 break;
10932 case AArch64CC::EQ:
10933 case AArch64CC::NE:
10934 if ((AddConstant > 0 && CompConstant < 0) ||
10935 (AddConstant < 0 && CompConstant >= 0 &&
10936 CompConstant < AddConstant + MaxUInt) ||
10937 (AddConstant >= 0 && CompConstant >= 0 &&
10938 CompConstant >= AddConstant) ||
10939 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
10940 return true;
10941 break;
10942 case AArch64CC::VS:
10943 case AArch64CC::VC:
10944 case AArch64CC::AL:
10945 case AArch64CC::NV:
10946 return true;
10947 case AArch64CC::Invalid:
10948 break;
10949 }
10950
10951 return false;
10952}
10953
10954static
10955SDValue performCONDCombine(SDNode *N,
10956 TargetLowering::DAGCombinerInfo &DCI,
10957 SelectionDAG &DAG, unsigned CCIndex,
10958 unsigned CmpIndex) {
10959 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10960 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10961 unsigned CondOpcode = SubsNode->getOpcode();
10962
10963 if (CondOpcode != AArch64ISD::SUBS)
10964 return SDValue();
10965
10966 // There is a SUBS feeding this condition. Is it fed by a mask we can
10967 // use?
10968
10969 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10970 unsigned MaskBits = 0;
10971
10972 if (AndNode->getOpcode() != ISD::AND)
10973 return SDValue();
10974
10975 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10976 uint32_t CNV = CN->getZExtValue();
10977 if (CNV == 255)
10978 MaskBits = 8;
10979 else if (CNV == 65535)
10980 MaskBits = 16;
10981 }
10982
10983 if (!MaskBits)
10984 return SDValue();
10985
10986 SDValue AddValue = AndNode->getOperand(0);
10987
10988 if (AddValue.getOpcode() != ISD::ADD)
10989 return SDValue();
10990
10991 // The basic dag structure is correct, grab the inputs and validate them.
10992
10993 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10994 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10995 SDValue SubsInputValue = SubsNode->getOperand(1);
10996
10997 // The mask is present and the provenance of all the values is a smaller type,
10998 // lets see if the mask is superfluous.
10999
11000 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11001 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11002 return SDValue();
11003
11004 ISD::LoadExtType ExtType;
11005
11006 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11007 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11008 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11009 return SDValue();
11010
11011 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11012 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11013 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11014 return SDValue();
11015
11016 // The AND is not necessary, remove it.
11017
11018 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11019 SubsNode->getValueType(1));
11020 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11021
11022 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11023 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11024
11025 return SDValue(N, 0);
11026}
11027
11028// Optimize compare with zero and branch.
11029static SDValue performBRCONDCombine(SDNode *N,
11030 TargetLowering::DAGCombinerInfo &DCI,
11031 SelectionDAG &DAG) {
11032 MachineFunction &MF = DAG.getMachineFunction();
11033 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11034 // will not be produced, as they are conditional branch instructions that do
11035 // not set flags.
11036 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11037 return SDValue();
11038
11039 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11040 N = NV.getNode();
11041 SDValue Chain = N->getOperand(0);
11042 SDValue Dest = N->getOperand(1);
11043 SDValue CCVal = N->getOperand(2);
11044 SDValue Cmp = N->getOperand(3);
11045
11046 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11047 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11048 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11049 return SDValue();
11050
11051 unsigned CmpOpc = Cmp.getOpcode();
11052 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11053 return SDValue();
11054
11055 // Only attempt folding if there is only one use of the flag and no use of the
11056 // value.
11057 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11058 return SDValue();
11059
11060 SDValue LHS = Cmp.getOperand(0);
11061 SDValue RHS = Cmp.getOperand(1);
11062
11063 assert(LHS.getValueType() == RHS.getValueType() &&
11064 "Expected the value type to be the same for both operands!");
11065 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11066 return SDValue();
11067
11068 if (isNullConstant(LHS))
11069 std::swap(LHS, RHS);
11070
11071 if (!isNullConstant(RHS))
11072 return SDValue();
11073
11074 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11075 LHS.getOpcode() == ISD::SRL)
11076 return SDValue();
11077
11078 // Fold the compare into the branch instruction.
11079 SDValue BR;
11080 if (CC == AArch64CC::EQ)
11081 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11082 else
11083 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11084
11085 // Do not add new nodes to DAG combiner worklist.
11086 DCI.CombineTo(N, BR, false);
11087
11088 return SDValue();
11089}
11090
11091// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11092// as well as whether the test should be inverted. This code is required to
11093// catch these cases (as opposed to standard dag combines) because
11094// AArch64ISD::TBZ is matched during legalization.
11095static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11096 SelectionDAG &DAG) {
11097
11098 if (!Op->hasOneUse())
11099 return Op;
11100
11101 // We don't handle undef/constant-fold cases below, as they should have
11102 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11103 // etc.)
11104
11105 // (tbz (trunc x), b) -> (tbz x, b)
11106 // This case is just here to enable more of the below cases to be caught.
11107 if (Op->getOpcode() == ISD::TRUNCATE &&
11108 Bit < Op->getValueType(0).getSizeInBits()) {
11109 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11110 }
11111
11112 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11113 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11114 Bit < Op->getOperand(0).getValueSizeInBits()) {
11115 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11116 }
11117
11118 if (Op->getNumOperands() != 2)
11119 return Op;
11120
11121 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11122 if (!C)
11123 return Op;
11124
11125 switch (Op->getOpcode()) {
11126 default:
11127 return Op;
11128
11129 // (tbz (and x, m), b) -> (tbz x, b)
11130 case ISD::AND:
11131 if ((C->getZExtValue() >> Bit) & 1)
11132 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11133 return Op;
11134
11135 // (tbz (shl x, c), b) -> (tbz x, b-c)
11136 case ISD::SHL:
11137 if (C->getZExtValue() <= Bit &&
11138 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11139 Bit = Bit - C->getZExtValue();
11140 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11141 }
11142 return Op;
11143
11144 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11145 case ISD::SRA:
11146 Bit = Bit + C->getZExtValue();
11147 if (Bit >= Op->getValueType(0).getSizeInBits())
11148 Bit = Op->getValueType(0).getSizeInBits() - 1;
11149 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11150
11151 // (tbz (srl x, c), b) -> (tbz x, b+c)
11152 case ISD::SRL:
11153 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11154 Bit = Bit + C->getZExtValue();
11155 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11156 }
11157 return Op;
11158
11159 // (tbz (xor x, -1), b) -> (tbnz x, b)
11160 case ISD::XOR:
11161 if ((C->getZExtValue() >> Bit) & 1)
11162 Invert = !Invert;
11163 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11164 }
11165}
11166
11167// Optimize test single bit zero/non-zero and branch.
11168static SDValue performTBZCombine(SDNode *N,
11169 TargetLowering::DAGCombinerInfo &DCI,
11170 SelectionDAG &DAG) {
11171 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11172 bool Invert = false;
11173 SDValue TestSrc = N->getOperand(1);
11174 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11175
11176 if (TestSrc == NewTestSrc)
11177 return SDValue();
11178
11179 unsigned NewOpc = N->getOpcode();
11180 if (Invert) {
11181 if (NewOpc == AArch64ISD::TBZ)
11182 NewOpc = AArch64ISD::TBNZ;
11183 else {
11184 assert(NewOpc == AArch64ISD::TBNZ);
11185 NewOpc = AArch64ISD::TBZ;
11186 }
11187 }
11188
11189 SDLoc DL(N);
11190 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11191 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11192}
11193
11194// vselect (v1i1 setcc) ->
11195// vselect (v1iXX setcc) (XX is the size of the compared operand type)
11196// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11197// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11198// such VSELECT.
11199static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11200 SDValue N0 = N->getOperand(0);
11201 EVT CCVT = N0.getValueType();
11202
11203 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11204 CCVT.getVectorElementType() != MVT::i1)
11205 return SDValue();
11206
11207 EVT ResVT = N->getValueType(0);
11208 EVT CmpVT = N0.getOperand(0).getValueType();
11209 // Only combine when the result type is of the same size as the compared
11210 // operands.
11211 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11212 return SDValue();
11213
11214 SDValue IfTrue = N->getOperand(1);
11215 SDValue IfFalse = N->getOperand(2);
11216 SDValue SetCC =
11217 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11218 N0.getOperand(0), N0.getOperand(1),
11219 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11220 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11221 IfTrue, IfFalse);
11222}
11223
11224/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11225/// the compare-mask instructions rather than going via NZCV, even if LHS and
11226/// RHS are really scalar. This replaces any scalar setcc in the above pattern
11227/// with a vector one followed by a DUP shuffle on the result.
11228static SDValue performSelectCombine(SDNode *N,
11229 TargetLowering::DAGCombinerInfo &DCI) {
11230 SelectionDAG &DAG = DCI.DAG;
11231 SDValue N0 = N->getOperand(0);
11232 EVT ResVT = N->getValueType(0);
11233
11234 if (N0.getOpcode() != ISD::SETCC)
11235 return SDValue();
11236
11237 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11238 // scalar SetCCResultType. We also don't expect vectors, because we assume
11239 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11240 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11241 "Scalar-SETCC feeding SELECT has unexpected result type!");
11242
11243 // If NumMaskElts == 0, the comparison is larger than select result. The
11244 // largest real NEON comparison is 64-bits per lane, which means the result is
11245 // at most 32-bits and an illegal vector. Just bail out for now.
11246 EVT SrcVT = N0.getOperand(0).getValueType();
11247
11248 // Don't try to do this optimization when the setcc itself has i1 operands.
11249 // There are no legal vectors of i1, so this would be pointless.
11250 if (SrcVT == MVT::i1)
11251 return SDValue();
11252
11253 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
11254 if (!ResVT.isVector() || NumMaskElts == 0)
11255 return SDValue();
11256
11257 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
11258 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11259
11260 // Also bail out if the vector CCVT isn't the same size as ResVT.
11261 // This can happen if the SETCC operand size doesn't divide the ResVT size
11262 // (e.g., f64 vs v3f32).
11263 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11264 return SDValue();
11265
11266 // Make sure we didn't create illegal types, if we're not supposed to.
11267 assert(DCI.isBeforeLegalize() ||
11268 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11269
11270 // First perform a vector comparison, where lane 0 is the one we're interested
11271 // in.
11272 SDLoc DL(N0);
11273 SDValue LHS =
11274 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11275 SDValue RHS =
11276 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11277 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11278
11279 // Now duplicate the comparison mask we want across all other lanes.
11280 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11281 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11282 Mask = DAG.getNode(ISD::BITCAST, DL,
11283 ResVT.changeVectorElementTypeToInteger(), Mask);
11284
11285 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11286}
11287
11288/// Get rid of unnecessary NVCASTs (that don't change the type).
11289static SDValue performNVCASTCombine(SDNode *N) {
11290 if (N->getValueType(0) == N->getOperand(0).getValueType())
11291 return N->getOperand(0);
11292
11293 return SDValue();
11294}
11295
11296// If all users of the globaladdr are of the form (globaladdr + constant), find
11297// the smallest constant, fold it into the globaladdr's offset and rewrite the
11298// globaladdr as (globaladdr + constant) - constant.
11299static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11300 const AArch64Subtarget *Subtarget,
11301 const TargetMachine &TM) {
11302 auto *GN = cast<GlobalAddressSDNode>(N);
11303 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11304 AArch64II::MO_NO_FLAG)
11305 return SDValue();
11306
11307 uint64_t MinOffset = -1ull;
11308 for (SDNode *N : GN->uses()) {
11309 if (N->getOpcode() != ISD::ADD)
11310 return SDValue();
11311 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11312 if (!C)
11313 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11314 if (!C)
11315 return SDValue();
11316 MinOffset = std::min(MinOffset, C->getZExtValue());
11317 }
11318 uint64_t Offset = MinOffset + GN->getOffset();
11319
11320 // Require that the new offset is larger than the existing one. Otherwise, we
11321 // can end up oscillating between two possible DAGs, for example,
11322 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11323 if (Offset <= uint64_t(GN->getOffset()))
11324 return SDValue();
11325
11326 // Check whether folding this offset is legal. It must not go out of bounds of
11327 // the referenced object to avoid violating the code model, and must be
11328 // smaller than 2^21 because this is the largest offset expressible in all
11329 // object formats.
11330 //
11331 // This check also prevents us from folding negative offsets, which will end
11332 // up being treated in the same way as large positive ones. They could also
11333 // cause code model violations, and aren't really common enough to matter.
11334 if (Offset >= (1 << 21))
11335 return SDValue();
11336
11337 const GlobalValue *GV = GN->getGlobal();
11338 Type *T = GV->getValueType();
11339 if (!T->isSized() ||
11340 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11341 return SDValue();
11342
11343 SDLoc DL(GN);
11344 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11345 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11346 DAG.getConstant(MinOffset, DL, MVT::i64));
11347}
11348
11349SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11350 DAGCombinerInfo &DCI) const {
11351 SelectionDAG &DAG = DCI.DAG;
11352 switch (N->getOpcode()) {
11353 default:
11354 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11355 break;
11356 case ISD::ADD:
11357 case ISD::SUB:
11358 return performAddSubLongCombine(N, DCI, DAG);
11359 case ISD::XOR:
11360 return performXorCombine(N, DAG, DCI, Subtarget);
11361 case ISD::MUL:
11362 return performMulCombine(N, DAG, DCI, Subtarget);
11363 case ISD::SINT_TO_FP:
11364 case ISD::UINT_TO_FP:
11365 return performIntToFpCombine(N, DAG, Subtarget);
11366 case ISD::FP_TO_SINT:
11367 case ISD::FP_TO_UINT:
11368 return performFpToIntCombine(N, DAG, DCI, Subtarget);
11369 case ISD::FDIV:
11370 return performFDivCombine(N, DAG, DCI, Subtarget);
11371 case ISD::OR:
11372 return performORCombine(N, DCI, Subtarget);
11373 case ISD::AND:
11374 return performANDCombine(N, DCI);
11375 case ISD::SRL:
11376 return performSRLCombine(N, DCI);
11377 case ISD::INTRINSIC_WO_CHAIN:
11378 return performIntrinsicCombine(N, DCI, Subtarget);
11379 case ISD::ANY_EXTEND:
11380 case ISD::ZERO_EXTEND:
11381 case ISD::SIGN_EXTEND:
11382 return performExtendCombine(N, DCI, DAG);
11383 case ISD::BITCAST:
11384 return performBitcastCombine(N, DCI, DAG);
11385 case ISD::CONCAT_VECTORS:
11386 return performConcatVectorsCombine(N, DCI, DAG);
11387 case ISD::SELECT:
11388 return performSelectCombine(N, DCI);
11389 case ISD::VSELECT:
11390 return performVSelectCombine(N, DCI.DAG);
11391 case ISD::LOAD:
11392 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11393 return SDValue(N, 0);
11394 break;
11395 case ISD::STORE:
11396 return performSTORECombine(N, DCI, DAG, Subtarget);
11397 case AArch64ISD::BRCOND:
11398 return performBRCONDCombine(N, DCI, DAG);
11399 case AArch64ISD::TBNZ:
11400 case AArch64ISD::TBZ:
11401 return performTBZCombine(N, DCI, DAG);
11402 case AArch64ISD::CSEL:
11403 return performCONDCombine(N, DCI, DAG, 2, 3);
11404 case AArch64ISD::DUP:
11405 return performPostLD1Combine(N, DCI, false);
11406 case AArch64ISD::NVCAST:
11407 return performNVCASTCombine(N);
11408 case ISD::INSERT_VECTOR_ELT:
11409 return performPostLD1Combine(N, DCI, true);
11410 case ISD::INTRINSIC_VOID:
11411 case ISD::INTRINSIC_W_CHAIN:
11412 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11413 case Intrinsic::aarch64_neon_ld2:
11414 case Intrinsic::aarch64_neon_ld3:
11415 case Intrinsic::aarch64_neon_ld4:
11416 case Intrinsic::aarch64_neon_ld1x2:
11417 case Intrinsic::aarch64_neon_ld1x3:
11418 case Intrinsic::aarch64_neon_ld1x4:
11419 case Intrinsic::aarch64_neon_ld2lane:
11420 case Intrinsic::aarch64_neon_ld3lane:
11421 case Intrinsic::aarch64_neon_ld4lane:
11422 case Intrinsic::aarch64_neon_ld2r:
11423 case Intrinsic::aarch64_neon_ld3r:
11424 case Intrinsic::aarch64_neon_ld4r:
11425 case Intrinsic::aarch64_neon_st2:
11426 case Intrinsic::aarch64_neon_st3:
11427 case Intrinsic::aarch64_neon_st4:
11428 case Intrinsic::aarch64_neon_st1x2:
11429 case Intrinsic::aarch64_neon_st1x3:
11430 case Intrinsic::aarch64_neon_st1x4:
11431 case Intrinsic::aarch64_neon_st2lane:
11432 case Intrinsic::aarch64_neon_st3lane:
11433 case Intrinsic::aarch64_neon_st4lane:
11434 return performNEONPostLDSTCombine(N, DCI, DAG);
11435 default:
11436 break;
11437 }
11438 break;
11439 case ISD::GlobalAddress:
11440 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11441 }
11442 return SDValue();
11443}
11444
11445// Check if the return value is used as only a return value, as otherwise
11446// we can't perform a tail-call. In particular, we need to check for
11447// target ISD nodes that are returns and any other "odd" constructs
11448// that the generic analysis code won't necessarily catch.
11449bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11450 SDValue &Chain) const {
11451 if (N->getNumValues() != 1)
11452 return false;
11453 if (!N->hasNUsesOfValue(1, 0))
11454 return false;
11455
11456 SDValue TCChain = Chain;
11457 SDNode *Copy = *N->use_begin();
11458 if (Copy->getOpcode() == ISD::CopyToReg) {
11459 // If the copy has a glue operand, we conservatively assume it isn't safe to
11460 // perform a tail call.
11461 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11462 MVT::Glue)
11463 return false;
11464 TCChain = Copy->getOperand(0);
11465 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11466 return false;
11467
11468 bool HasRet = false;
11469 for (SDNode *Node : Copy->uses()) {
11470 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11471 return false;
11472 HasRet = true;
11473 }
11474
11475 if (!HasRet)
11476 return false;
11477
11478 Chain = TCChain;
11479 return true;
11480}
11481
11482// Return whether the an instruction can potentially be optimized to a tail
11483// call. This will cause the optimizers to attempt to move, or duplicate,
11484// return instructions to help enable tail call optimizations for this
11485// instruction.
11486bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11487 return CI->isTailCall();
11488}
11489
11490bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11491 SDValue &Offset,
11492 ISD::MemIndexedMode &AM,
11493 bool &IsInc,
11494 SelectionDAG &DAG) const {
11495 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11496 return false;
11497
11498 Base = Op->getOperand(0);
11499 // All of the indexed addressing mode instructions take a signed
11500 // 9 bit immediate offset.
11501 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11502 int64_t RHSC = RHS->getSExtValue();
11503 if (Op->getOpcode() == ISD::SUB)
11504 RHSC = -(uint64_t)RHSC;
11505 if (!isInt<9>(RHSC))
11506 return false;
11507 IsInc = (Op->getOpcode() == ISD::ADD);
11508 Offset = Op->getOperand(1);
11509 return true;
11510 }
11511 return false;
11512}
11513
11514bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11515 SDValue &Offset,
11516 ISD::MemIndexedMode &AM,
11517 SelectionDAG &DAG) const {
11518 EVT VT;
11519 SDValue Ptr;
11520 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11521 VT = LD->getMemoryVT();
11522 Ptr = LD->getBasePtr();
11523 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11524 VT = ST->getMemoryVT();
11525 Ptr = ST->getBasePtr();
11526 } else
11527 return false;
11528
11529 bool IsInc;
11530 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11531 return false;
11532 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11533 return true;
11534}
11535
11536bool AArch64TargetLowering::getPostIndexedAddressParts(
11537 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11538 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11539 EVT VT;
11540 SDValue Ptr;
11541 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11542 VT = LD->getMemoryVT();
11543 Ptr = LD->getBasePtr();
11544 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11545 VT = ST->getMemoryVT();
11546 Ptr = ST->getBasePtr();
11547 } else
11548 return false;
11549
11550 bool IsInc;
11551 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11552 return false;
11553 // Post-indexing updates the base, so it's not a valid transform
11554 // if that's not the same as the load's pointer.
11555 if (Ptr != Base)
11556 return false;
11557 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11558 return true;
11559}
11560
11561static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11562 SelectionDAG &DAG) {
11563 SDLoc DL(N);
11564 SDValue Op = N->getOperand(0);
11565
11566 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11567 return;
11568
11569 Op = SDValue(
11570 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11571 DAG.getUNDEF(MVT::i32), Op,
11572 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11573 0);
11574 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11575 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11576}
11577
11578static void ReplaceReductionResults(SDNode *N,
11579 SmallVectorImpl<SDValue> &Results,
11580 SelectionDAG &DAG, unsigned InterOp,
11581 unsigned AcrossOp) {
11582 EVT LoVT, HiVT;
11583 SDValue Lo, Hi;
11584 SDLoc dl(N);
11585 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11586 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11587 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11588 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11589 Results.push_back(SplitVal);
11590}
11591
11592static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11593 SDLoc DL(N);
11594 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11595 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11596 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11597 DAG.getConstant(64, DL, MVT::i64)));
11598 return std::make_pair(Lo, Hi);
11599}
11600
11601// Create an even/odd pair of X registers holding integer value V.
11602static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11603 SDLoc dl(V.getNode());
11604 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11605 SDValue VHi = DAG.getAnyExtOrTrunc(
11606 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11607 dl, MVT::i64);
11608 if (DAG.getDataLayout().isBigEndian())
11609 std::swap (VLo, VHi);
11610 SDValue RegClass =
11611 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11612 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11613 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11614 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11615 return SDValue(
11616 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11617}
11618
11619static void ReplaceCMP_SWAP_128Results(SDNode *N,
11620 SmallVectorImpl<SDValue> &Results,
11621 SelectionDAG &DAG,
11622 const AArch64Subtarget *Subtarget) {
11623 assert(N->getValueType(0) == MVT::i128 &&
11624 "AtomicCmpSwap on types less than 128 should be legal");
11625
11626 if (Subtarget->hasLSE()) {
11627 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11628 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11629 SDValue Ops[] = {
11630 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11631 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11632 N->getOperand(1), // Ptr
11633 N->getOperand(0), // Chain in
11634 };
11635
11636 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11637
11638 unsigned Opcode;
11639 switch (MemOp->getOrdering()) {
11640 case AtomicOrdering::Monotonic:
11641 Opcode = AArch64::CASPX;
11642 break;
11643 case AtomicOrdering::Acquire:
11644 Opcode = AArch64::CASPAX;
11645 break;
11646 case AtomicOrdering::Release:
11647 Opcode = AArch64::CASPLX;
11648 break;
11649 case AtomicOrdering::AcquireRelease:
11650 case AtomicOrdering::SequentiallyConsistent:
11651 Opcode = AArch64::CASPALX;
11652 break;
11653 default:
11654 llvm_unreachable("Unexpected ordering!");
11655 }
11656
11657 MachineSDNode *CmpSwap = DAG.getMachineNode(
11658 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11659 DAG.setNodeMemRefs(CmpSwap, {MemOp});
11660
11661 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11662 if (DAG.getDataLayout().isBigEndian())
11663 std::swap(SubReg1, SubReg2);
11664 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11665 SDValue(CmpSwap, 0)));
11666 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11667 SDValue(CmpSwap, 0)));
11668 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11669 return;
11670 }
11671
11672 auto Desired = splitInt128(N->getOperand(2), DAG);
11673 auto New = splitInt128(N->getOperand(3), DAG);
11674 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11675 New.first, New.second, N->getOperand(0)};
11676 SDNode *CmpSwap = DAG.getMachineNode(
11677 AArch64::CMP_SWAP_128, SDLoc(N),
11678 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11679
11680 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11681 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11682
11683 Results.push_back(SDValue(CmpSwap, 0));
11684 Results.push_back(SDValue(CmpSwap, 1));
11685 Results.push_back(SDValue(CmpSwap, 3));
11686}
11687
11688void AArch64TargetLowering::ReplaceNodeResults(
11689 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11690 switch (N->getOpcode()) {
11691 default:
11692 llvm_unreachable("Don't know how to custom expand this");
11693 case ISD::BITCAST:
11694 ReplaceBITCASTResults(N, Results, DAG);
11695 return;
11696 case ISD::VECREDUCE_ADD:
11697 case ISD::VECREDUCE_SMAX:
11698 case ISD::VECREDUCE_SMIN:
11699 case ISD::VECREDUCE_UMAX:
11700 case ISD::VECREDUCE_UMIN:
11701 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11702 return;
11703
11704 case AArch64ISD::SADDV:
11705 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11706 return;
11707 case AArch64ISD::UADDV:
11708 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11709 return;
11710 case AArch64ISD::SMINV:
11711 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11712 return;
11713 case AArch64ISD::UMINV:
11714 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11715 return;
11716 case AArch64ISD::SMAXV:
11717 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11718 return;
11719 case AArch64ISD::UMAXV:
11720 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11721 return;
11722 case ISD::FP_TO_UINT:
11723 case ISD::FP_TO_SINT:
11724 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11725 // Let normal code take care of it by not adding anything to Results.
11726 return;
11727 case ISD::ATOMIC_CMP_SWAP:
11728 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
11729 return;
11730 }
11731}
11732
11733bool AArch64TargetLowering::useLoadStackGuardNode() const {
11734 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11735 return TargetLowering::useLoadStackGuardNode();
11736 return true;
11737}
11738
11739unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11740 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11741 // reciprocal if there are three or more FDIVs.
11742 return 3;
11743}
11744
11745TargetLoweringBase::LegalizeTypeAction
11746AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
11747 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11748 // v4i16, v2i32 instead of to promote.
11749 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11750 VT == MVT::v1f32)
11751 return TypeWidenVector;
11752
11753 return TargetLoweringBase::getPreferredVectorAction(VT);
11754}
11755
11756// Loads and stores less than 128-bits are already atomic; ones above that
11757// are doomed anyway, so defer to the default libcall and blame the OS when
11758// things go wrong.
11759bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11760 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11761 return Size == 128;
11762}
11763
11764// Loads and stores less than 128-bits are already atomic; ones above that
11765// are doomed anyway, so defer to the default libcall and blame the OS when
11766// things go wrong.
11767TargetLowering::AtomicExpansionKind
11768AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11769 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11770 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
11771}
11772
11773// For the real atomic operations, we have ldxr/stxr up to 128 bits,
11774TargetLowering::AtomicExpansionKind
11775AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11776 if (AI->isFloatingPointOperation())
11777 return AtomicExpansionKind::CmpXChg;
11778
11779 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11780 if (Size > 128) return AtomicExpansionKind::None;
11781 // Nand not supported in LSE.
11782 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
11783 // Leave 128 bits to LLSC.
11784 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
11785}
11786
11787TargetLowering::AtomicExpansionKind
11788AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11789 AtomicCmpXchgInst *AI) const {
11790 // If subtarget has LSE, leave cmpxchg intact for codegen.
11791 if (Subtarget->hasLSE())
11792 return AtomicExpansionKind::None;
11793 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11794 // implement cmpxchg without spilling. If the address being exchanged is also
11795 // on the stack and close enough to the spill slot, this can lead to a
11796 // situation where the monitor always gets cleared and the atomic operation
11797 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11798 if (getTargetMachine().getOptLevel() == 0)
11799 return AtomicExpansionKind::None;
11800 return AtomicExpansionKind::LLSC;
11801}
11802
11803Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11804 AtomicOrdering Ord) const {
11805 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11806 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11807 bool IsAcquire = isAcquireOrStronger(Ord);
11808
11809 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11810 // intrinsic must return {i64, i64} and we have to recombine them into a
11811 // single i128 here.
11812 if (ValTy->getPrimitiveSizeInBits() == 128) {
11813 Intrinsic::ID Int =
11814 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
11815 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
11816
11817 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11818 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11819
11820 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11821 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11822 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11823 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11824 return Builder.CreateOr(
11825 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11826 }
11827
11828 Type *Tys[] = { Addr->getType() };
11829 Intrinsic::ID Int =
11830 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
11831 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
11832
11833 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11834
11835 const DataLayout &DL = M->getDataLayout();
11836 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11837 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11838
11839 return Builder.CreateBitCast(Trunc, EltTy);
11840}
11841
11842void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11843 IRBuilder<> &Builder) const {
11844 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11845 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
11846}
11847
11848Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11849 Value *Val, Value *Addr,
11850 AtomicOrdering Ord) const {
11851 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11852 bool IsRelease = isReleaseOrStronger(Ord);
11853
11854 // Since the intrinsics must have legal type, the i128 intrinsics take two
11855 // parameters: "i64, i64". We must marshal Val into the appropriate form
11856 // before the call.
11857 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11858 Intrinsic::ID Int =
11859 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11860 Function *Stxr = Intrinsic::getDeclaration(M, Int);
11861 Type *Int64Ty = Type::getInt64Ty(M->getContext());
11862
11863 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11864 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11865 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11866 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
11867 }
11868
11869 Intrinsic::ID Int =
11870 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
11871 Type *Tys[] = { Addr->getType() };
11872 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
11873
11874 const DataLayout &DL = M->getDataLayout();
11875 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
11876 Val = Builder.CreateBitCast(Val, IntValTy);
11877
11878 return Builder.CreateCall(Stxr,
11879 {Builder.CreateZExtOrBitCast(
11880 Val, Stxr->getFunctionType()->getParamType(0)),
11881 Addr});
11882}
11883
11884bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
11885 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11886 return Ty->isArrayTy();
11887}
11888
11889bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
11890 EVT) const {
11891 return false;
11892}
11893
11894static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
11895 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
11896 Function *ThreadPointerFunc =
11897 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
11898 return IRB.CreatePointerCast(
11899 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
11900 Offset),
11901 IRB.getInt8PtrTy()->getPointerTo(0));
11902}
11903
11904Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
11905 // Android provides a fixed TLS slot for the stack cookie. See the definition
11906 // of TLS_SLOT_STACK_GUARD in
11907 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11908 if (Subtarget->isTargetAndroid())
11909 return UseTlsOffset(IRB, 0x28);
11910
11911 // Fuchsia is similar.
11912 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
11913 if (Subtarget->isTargetFuchsia())
11914 return UseTlsOffset(IRB, -0x10);
11915
11916 return TargetLowering::getIRStackGuard(IRB);
11917}
11918
11919void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
11920 // MSVC CRT provides functionalities for stack protection.
11921 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
11922 // MSVC CRT has a global variable holding security cookie.
11923 M.getOrInsertGlobal("__security_cookie",
11924 Type::getInt8PtrTy(M.getContext()));
11925
11926 // MSVC CRT has a function to validate security cookie.
11927 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
11928 "__security_check_cookie", Type::getVoidTy(M.getContext()),
11929 Type::getInt8PtrTy(M.getContext()));
11930 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
11931 F->setCallingConv(CallingConv::Win64);
11932 F->addAttribute(1, Attribute::AttrKind::InReg);
11933 }
11934 return;
11935 }
11936 TargetLowering::insertSSPDeclarations(M);
11937}
11938
11939Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
11940 // MSVC CRT has a global variable holding security cookie.
11941 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11942 return M.getGlobalVariable("__security_cookie");
11943 return TargetLowering::getSDagStackGuard(M);
11944}
11945
11946Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
11947 // MSVC CRT has a function to validate security cookie.
11948 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
11949 return M.getFunction("__security_check_cookie");
11950 return TargetLowering::getSSPStackGuardCheck(M);
11951}
11952
11953Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
11954 // Android provides a fixed TLS slot for the SafeStack pointer. See the
11955 // definition of TLS_SLOT_SAFESTACK in
11956 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
11957 if (Subtarget->isTargetAndroid())
11958 return UseTlsOffset(IRB, 0x48);
11959
11960 // Fuchsia is similar.
11961 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
11962 if (Subtarget->isTargetFuchsia())
11963 return UseTlsOffset(IRB, -0x8);
11964
11965 return TargetLowering::getSafeStackPointerLocation(IRB);
11966}
11967
11968bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
11969 const Instruction &AndI) const {
11970 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
11971 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
11972 // may be beneficial to sink in other cases, but we would have to check that
11973 // the cmp would not get folded into the br to form a cbz for these to be
11974 // beneficial.
11975 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
11976 if (!Mask)
11977 return false;
11978 return Mask->getValue().isPowerOf2();
11979}
11980
11981void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11982 // Update IsSplitCSR in AArch64unctionInfo.
11983 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
11984 AFI->setIsSplitCSR(true);
11985}
11986
11987void AArch64TargetLowering::insertCopiesSplitCSR(
11988 MachineBasicBlock *Entry,
11989 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11990 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11991 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11992 if (!IStart)
11993 return;
11994
11995 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11996 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
11997 MachineBasicBlock::iterator MBBI = Entry->begin();
11998 for (const MCPhysReg *I = IStart; *I; ++I) {
11999 const TargetRegisterClass *RC = nullptr;
12000 if (AArch64::GPR64RegClass.contains(*I))
12001 RC = &AArch64::GPR64RegClass;
12002 else if (AArch64::FPR64RegClass.contains(*I))
12003 RC = &AArch64::FPR64RegClass;
12004 else
12005 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12006
12007 unsigned NewVR = MRI->createVirtualRegister(RC);
12008 // Create copy from CSR to a virtual register.
12009 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12010 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12011 // nounwind. If we want to generalize this later, we may need to emit
12012 // CFI pseudo-instructions.
12013 assert(Entry->getParent()->getFunction().hasFnAttribute(
12014 Attribute::NoUnwind) &&
12015 "Function should be nounwind in insertCopiesSplitCSR!");
12016 Entry->addLiveIn(*I);
12017 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12018 .addReg(*I);
12019
12020 // Insert the copy-back instructions right before the terminator.
12021 for (auto *Exit : Exits)
12022 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12023 TII->get(TargetOpcode::COPY), *I)
12024 .addReg(NewVR);
12025 }
12026}
12027
12028bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
12029 // Integer division on AArch64 is expensive. However, when aggressively
12030 // optimizing for code size, we prefer to use a div instruction, as it is
12031 // usually smaller than the alternative sequence.
12032 // The exception to this is vector division. Since AArch64 doesn't have vector
12033 // integer division, leaving the division as-is is a loss even in terms of
12034 // size, because it will have to be scalarized, while the alternative code
12035 // sequence can be performed in vector form.
12036 bool OptSize =
12037 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
12038 return OptSize && !VT.isVector();
12039}
12040
12041bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12042 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12043}
12044
12045unsigned
12046AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL, unsigned AS) const {
12047 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
12048 return getPointerTy(DL, AS).getSizeInBits();
12049
12050 return 3 * getPointerTy(DL, AS).getSizeInBits() + 2 * 32;
12051}
12052
12053void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12054 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12055 TargetLoweringBase::finalizeLowering(MF);
12056}
12057
12058// Unlike X86, we let frame lowering assign offsets to all catch objects.
12059bool AArch64TargetLowering::needsFixedCatchObjects() const {
12060 return false;
12061}
12062